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.
要求prices[j]-prices[i]的最大值(j=i+1,i+2,i+3,……,n);
prices[j]-prices[i] = (prices[j]-prices[j-1]) + (prices[j-1]-prices[j-2]) + ……+(prices[i+1]-prices[i]);
因此求prices[k+1]-prices[k]的最大连续子和即为所求
public class Solution {
public int maxProfit(int[] prices) {
int ret = 0;
int tmp = 0;
for(int i=0;i<prices.length-1;i++){
if(tmp<0)
tmp = 0;
tmp+=prices[i+1]-prices[i];
ret = Math.max(ret, tmp);
}
return ret;
}
}