程序员

Leetcode - Best Time to Buy and

2016-09-23  本文已影响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;
    }
};
上一篇 下一篇

猜你喜欢

热点阅读