Best Time to Buy and Sell stock (Simple DP)
Giving an array of values, say the ith value is the price of stock of the ith day. If you can perform at most one transaction (ie. Buy one and sell one share of stock), find the maximum profit.
Keep tracing the minimum price before the ith day and calculating the maximum profit during scanning.
1 | public int maxProfit(int[] prices) { |
Best Time to Buy and Sell stock(Greed)
Giving an array of values, say the ith value is the price of stock of the ith day. If you can perform as many transactions (ie. Buy one and sell one share of stock) as you like, find the maximum profit.
Using greed algorithm, perform the transaction only if there is profit to make between two continuous days.
1 | public int maxProfit(int[] prices) { |
Best Time to Buy and Sell stock(Devide and Conquer & DP)
Giving an array of values, say the ith value is the price of stock of the ith day. If you can perform at most two transactions (ie. Buy one and sell one share of stock), find the maximum profit.
This can be solved by “Devide and Conquer”, using left array to track maximum profit by one transaction before the ith day, and right array to track maximum profit by one transaction after the ith day.
1 | public int maxProfit(int[] prices) { |
Best Time to Buy and Sell stock(2D DP)
Giving an array of values, say the ith value is the price of stock of the ith day. If you can perform at most k transactions (ie. Buy one and sell one share of stock), find the maximum profit.
Using 2D dynamic programming, dp[i][j] means maximum profit until ith transaction and jth day.
1 | public int maxProfit(int k, int[] prices) { |
Reference
https://leetcode.com/discuss/25603/a-concise-dp-solution-in-java