题目如下:
1.
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.
» Solve this problem
2.
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
» Solve this problem
3.
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most two transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
方法:
第一题是O(1)的DP题,第二题比第一题还简单,可以说是整个leetcode上为数不多的简单题,第三题非常好,用了一个双层一维DP。值得学习。
Code:
1.
public class Solution {
public int maxProfit(int[] prices) {
// Start typing your Java solution below
// DO NOT write main() function
if(prices == null || prices.length == 0) return 0;
int min = prices[0], res = 0;
for(int i=0; i<prices.length; i++){
if(prices[i] < min) min = prices[i];
res = Math.max(res, prices[i] - min);
}
return res;
}
}
2.
public class Solution {
public int maxProfit(int[] prices) {
// Start typing your Java solution below
// DO NOT write main() function
int res = 0;
for(int i=1; i<prices.length; i++)
res += prices[i]>prices[i-1]?(prices[i]-prices[i-1]):0;
return res;
}
}
3.
public class Solution {
public int maxProfit(int[] prices) {
// Start typing your Java solution below
// DO NOT write main() function
if(prices == null || prices.length == 0) return 0;
int min = prices[0], max = prices[prices.length-1], res = 0;
int[] p1 = new int[prices.length], p2 = new int[prices.length];
for(int i=0; i<prices.length; i++){
if(prices[i] < min) min = prices[i];
p1[i] = Math.max(prices[i]-min, i>0?p1[i-1]:0);
}
for(int i=prices.length-1; i>=0; i--){
if(prices[i] > max) max = prices[i];
p2[i] = Math.max(max-prices[i], i<prices.length-1?p2[i+1]:0);
res = Math.max(p1[i]+p2[i], res);
}
return res;
}
}
总结:
第二题不用讨论,第一题很有趣,是个DP的入门,这个O(1)的min元素表示整个股票走向图的最低点,而遍历的动态过程只要考虑最低点就OK了。
第三题,循环两次,从前往后,从后往前,利用前面的结果结合后面的结果,得到最终数据。