买卖股票的最佳时机

描述:假设有一个数组,它的第i个元素是一支给定的股票在第i天的价格。如果你最多只允许完成一次交易(例如,一次买卖股票),设计一个算法来找出最大利润。

样例:给出一个数组样例 [3,2,3,1,2], 返回 1 

code:

class Solution {
public:
/**
* @param prices: Given an integer array
* @return: Maximum profit
*/
int maxProfit(vector<int> &prices) {
// write your code here
if(prices.empty())
return 0;            //输出为空,返回空值
int Max=0;
int Min =prices[0];

for (auto &e:prices){
if(e<Min)           //找到所有元素中最小值
Min=e;
else
Max=max(Max,e-Min);//不断寻找最大值
}
return Max;
}
};

思路:1st:输入的股票价格可能为零。

        2nd:首先找到元素中的的最小值,向前求减,直到找到最大值。

原文地址:https://www.cnblogs.com/Gobenk/p/6518822.html