问题描述
股票交易。数组第i个元素表示第i天股票的价格,整个过程只能买一次和卖一次,设计一个算法寻找最大收益。
例1:
Input: [7, 1, 5, 3, 6, 4]
Output: 5
只能先买进才能卖出,所以最大收益为6-1=5,而不是7-1=6。
例2:
Input: [7, 6, 4, 3, 1]
Output: 0
贪心。其实就是找一个数组里面的最大差值j-i,保证i < j即可。
//但是这个方法两重循环,超时了!
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size() == 0) return 0;
int result=0;
int temp=0;
for(int i=0;i<prices.size()-1;i++){
for(int j=i+1;j<prices.size();j++){
temp=prices[j]-prices[i];
result=max(result,temp);
}
}
return result;
}
};
Time Limit Exceeded:
Last executed input:
[10000,9999,9998,9997,9996,9995,9994,9993,9992,9991,9990,9989…….]
所以我们需要优化。
AC代码如下:
class Solution {
public:
int maxProfit(vector<int>& prices) {
int result=0; //始终记录最大值
int temp=0; //记录当天的收益,若为负,则置0重新计算收益(此时最大值已经被result保存下来了)
for(int i=1; i<prices.size(); i++){
temp += (prices[i]-prices[i-1]);
if(temp<0){
temp=0;
}
result=max(result,temp);
}
return result;
}
};