Skip to content

Instantly share code, notes, and snippets.

@Cee
Last active October 31, 2017 04:59
Show Gist options
  • Save Cee/073539d36fdd395d196bf129213f3e84 to your computer and use it in GitHub Desktop.
Save Cee/073539d36fdd395d196bf129213f3e84 to your computer and use it in GitHub Desktop.
30 lines to solve MaxProfit problem
public int maxProfit(int[] prices, int k, int day, int fee) {
int n = prices.length;
if (n == 0 || n == 1 || k == 0) {
return 0;
}
int[] buy = new int[n];
int[] sell = new int[n];
int[] oldSell = new int[n];
int maxProfit = 0;
for (int index = 1; index <= k; index++) {
buy[0] = -prices[0];
for (int i = 1; i < n; i++) {
if (i > day) {
buy[i]=(Math.max(buy[i - 1], oldSell[i - day - 1] - prices[i]));
} else {
buy[i]=(Math.max(buy[i - 1], -prices[i]));
}
sell[i]=(Math.max(buy[i - 1] + prices[i] - fee, sell[i - 1]));
}
maxProfit = Math.max(maxProfit, sell[n - 1]);
oldSell = sell.clone();
buy = new int[n];
sell = new int[n];
}
return maxProfit;
}
func maxProfit(_ prices: [Int], _ k: Int, _ day: Int, _ fee: Int) -> Int {
let n = prices.count
if n == 0 || n == 1 || k == 0 {
return 0
}
var buy: [Int] = []
var sell: [Int] = [0]
var oldSell: [Int] = [Int](repeating: 0, count: n)
var maxProfit = 0
for var index in 1...k {
buy.append(-prices[0])
for var i in 1..<n {
if i > day {
buy.append(max(buy[i - 1], oldSell[i - day - 1] - prices[i]))
} else {
buy.append(max(buy[i - 1], -prices[i]))
}
sell.append(max(buy[i - 1] + prices[i] - fee, sell[i - 1]))
}
maxProfit = max(maxProfit, sell[n - 1])
oldSell = sell
buy = []
sell = [0]
}
return maxProfit
}
@Cee
Copy link
Author

Cee commented Oct 31, 2017

Series of stock problems in LeetCode:

  1. 121. Best Time to Buy and Sell Stock: maxProfit(prices, 1, 0, 0)
  2. 122. Best Time to Buy and Sell Stock II: maxProfit(prices, prices.length / 2, 0, 0)
  3. 123. Best Time to Buy and Sell Stock III: maxProfit(prices, 2, 0, 0)
  4. 188. Best Time to Buy and Sell Stock IV: maxProfit(prices, Math.abs(k, prices.length / 2, 0, 0)
  5. 309. Best Time to Buy and Sell Stock with Cooldown: maxProfit(prices, prices.length / 2, 1, 0)
  6. 714. Best Time to Buy and Sell Stock with Transaction Fee: maxProfit(prices, prices.length / 2, 0, fee)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment