Last active
October 31, 2017 04:59
-
-
Save Cee/073539d36fdd395d196bf129213f3e84 to your computer and use it in GitHub Desktop.
30 lines to solve MaxProfit problem
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Series of stock problems in LeetCode:
maxProfit(prices, 1, 0, 0)
maxProfit(prices, prices.length / 2, 0, 0)
maxProfit(prices, 2, 0, 0)
maxProfit(prices, Math.abs(k, prices.length / 2, 0, 0)
maxProfit(prices, prices.length / 2, 1, 0)
maxProfit(prices, prices.length / 2, 0, fee)