Best Time to Buy and Sell Stock
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
思路:这道题就是让自己能得到最大的利润,举个例子{6,1,3,2,4,7},元素1和元素3得到利润为2,先保存起来,然后3到2少了1但是现在利润大于0,也是赚到了,后面一直到7,说明自己赚到(7-2)+(3-1)+(2-3)=6.所以每判断两个数相减如果大于0,则判断一次最大值;如果小于0,则将result置为0;
class Solution { public: int maxProfit(vector<int> &prices) { int nSize=prices.size(); if(nSize<=1) return 0; int result=0; int max=0; for(int i=1;i<nSize;i++) { result+=(prices[i]-prices[i-1]); if(result<0) result=0; if(max<result) max=result; } return max; } };