leecode第一百二十二题(买卖股票的最佳时机II)

leecode第一百二十二题(买卖股票的最佳时机II)

class Solution {
public:
int maxProfit(vector<int>& prices) {
int len=prices.size();
if(len<=)
return ; int sta=,lirun=;
while(sta<len-)
{
while(sta<len- && prices[sta]>prices[sta+])//找到当前第一个最小值
sta++;
if(sta==len- && prices[sta]>prices[sta+])
return lirun; int max_num=sta+;
while(max_num<len- && prices[max_num]<prices[max_num+])//找到第一个最小值后的第一个不小于后面的值
max_num++;
if(max_num==len- && prices[max_num]<prices[max_num+])
max_num++; lirun=lirun+prices[max_num]-prices[sta];//我们认为最近的利润是当前第一个最小值和第一个不输第二天的值的差,而这种利润的和不会少于全局唯一最大利润
sta=max_num+;
} return lirun;
}
};

分析:

思路有,但是一开始不确认正不正确,但是举的例子告诉我这样想目前是对的,于是就写了。

值的注意的是,while(max_num<len-2 && prices[max_num]<prices[max_num+1]),这句话里以后一定要先把值的边界性判断放前面,不然max_num+1超出边界,会提示错误。

上一篇:MySQL无法远程连接解决方案


下一篇:关于C++ 输入输出流状态控制