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.
分析:
看到最优化,想到动规,
找子问题:max[i] 是[ 0, i ] 的最大利润,可知 max[ 0 ] = 0,
状态转移方程: max[i] = max{max[i-1], prices[i]-min}, min是维持的最小股价。
最后,max[ len -1]就是要的答案。
public class Solution {
public int maxProfit(int[] prices) {
if(prices == null || prices.length<=1) return 0;
int[] max = new int[prices.length];
max[0] = 0;
int min = prices[0];
for(int i=1; i<prices.length; i++){
max[i] = Math.max(max[i-1], prices[i]-min);
min = Math.min(min, prices[i]);
}
return max[prices.length-1];
}
}