美文网首页程序员
Leetcode - Best Time to Buy and

Leetcode - Best Time to Buy and

作者: 哈比猪 | 来源:发表于2016-09-23 17:18 被阅读0次

题目链接

best-time-to-buy-and-sell-stock

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

解题思路

TODO(有时间补上,先把自己的leetcode代码写上供参考)

解题代码

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int maxProfit = 0;
        if (prices.empty()) return 0;
        int minEle = prices[0];
        int profit = 0;
        for(int i =1;i<prices.size();i++) {
            profit = (prices[i]-minEle) >= profit? (prices[i]-minEle):profit;
            minEle = minEle >=prices[i] ? prices[i]:minEle;
        }
        return profit;
    }
};

相关文章

网友评论

    本文标题:Leetcode - Best Time to Buy and

    本文链接:https://www.haomeiwen.com/subject/dkgtyttx.html