1. Best Time To Buy and Sell Stock
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.
public class Solution {
public int maxProfit(int[] prices) {
if(prices.length == 0) return 0;
int max = 0, min = Integer.MAX_VALUE;
for(int price: prices){
min = Math.min(min, price);
max = Math.max(max, price - min);
}
return max;
}
}
2. Best Time To Buy and Sell Stock II
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).
public class Solution {
public int maxProfit(int[] prices) {
int profit = 0;
for(int i = 1; i < prices.length; i ++){
if(prices[i] > prices[i-1])
profit += prices[i] - prices[i-1];
}
return profit;
}
}
3. Best Time To Buy and Sell Stock III
Design an algorithm to find the maximum profit.
You may complete at most two transactions.
public class Solution {
public int maxProfit(int[] prices) {
if(prices.length == 0) return 0;
int[] l = new int[2 + 1];
int[] g = new int[2 + 1];
for(int i = 1; i < prices.length; i ++){
int diff = prices[i] - prices[i - 1];
for(int j = 2; j > 0; j --){
l[j] = Math.max(l[j] + diff, g[j-1] + Math.max(0, diff));
g[j] = Math.max(l[j], g[j]);
}
}
return g[2];
}
}
4. Best Time To Buy and Sell Stock IV
Design an algorithm to find the maximum profit.
You may complete at most k transactions.
public class Solution {
public int maxProfit(int k, int[] prices) {
if(prices.length==0) return 0;
int n = prices.length;
if(k>=n) return solveMaxProfit(prices);
int[] l = new int[k + 1];
int[] g = new int[k + 1];
for(int i = 1; i < prices.length; i ++){
int diff = prices[i] - prices[i - 1];
for(int j = k; j > 0; j --){
l[j] = Math.max(l[j] + diff, g[j-1] + Math.max(0, diff));
g[j] = Math.max(l[j], g[j]);
}
}
return g[k];
}
public int solveMaxProfit(int[] prices) {
int res = 0;
for(int i=1; i<prices.length; i++){
if(prices[i] - prices[i-1]>0)
res += prices[i] - prices[i-1];
}
return res;
}
}