思路:
贪心算法。
时间复杂度O(n)。
遍历一遍数组。
如果还没有买入,则如果第二天比今天价格高则买入,否则向后走。
如果买入了,第二天价格比今天低,则卖出。
最后判断在最后一天的时候有没有买入,因为最后一天没有后续的第二天了,如果买了就直接卖出,因为既然会买进,那么说明在最后一次买肯定是后续卖出会赚钱。之前判断第二天和当前日子价格的差距决定是否卖出是为了贪心确定最佳卖出时间。
class Solution
{
public:
int maxProfit(vector<int>& prices)
{
int length=prices.size();
int buy;
bool isbuy=false;
bool issell=false;
int sell;
int sum=0;
int i;
for(i=0;i<length-1;i++)
{
if(!isbuy&&prices[i]<prices[i+1])
{
buy=prices[i];
isbuy=true;
continue;
}
if(isbuy&&prices[i]>prices[i+1])
{
isbuy=false;
sum=sum+prices[i]-buy;
// cout<<"buy "<<buy<<" sell "<<prices[i]<<" profit "<<prices[i]-buy<<endl;
continue;
}
else
{
continue;
}
}
if(i==length-1)
{
if(isbuy)
{
sum=sum+prices[length-1]-buy;
}
}
return sum;
}
};