买卖股票的最好时机

题目描述
假设你有一个数组,其中第\ i i 个元素是股票在第\ i i 天的价格。
你有一次买入和卖出的机会。(只有买入了股票以后才能卖出)。请你设计一个算法来计算可以获得的最大收益。

示例1
输入

[1,4,2]

返回值

3

示例2
输入

[2,4,1]

返回值

2
class Solution {
public:
    /**
     * 
     * @param prices int整型vector 
     * @return int整型
     */
    int maxProfit(vector<int>& prices) {
        // write code here
        int max = 0, min = prices[0];
        for(int i = 0; i < prices.size(); i++){
            min = min < prices[i] ? min : prices[i];
            max = max > (prices[i] - min) ? max : (prices[i] - min);
        }
        return max;
        
    }
    
//     int func_min(int &a, int &b){
//         if(a > b)
//     }
};

猜你喜欢

转载自blog.csdn.net/weixin_43599304/article/details/115309506