Leetcode - Best Time to Buy and Sell Stock

题目链接

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;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容