1. Best Time to Buy and Sell Stock
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.
Example 1:
1 | Input: [7, 1, 5, 3, 6, 4] |
Example 2:
1 | Input: [7, 6, 4, 3, 1] |
Answer:
for each time i with price = prices[i], we should find the minimum prices whose time j < i
1 | func MaxProfit(prices []int) int { |
2. Best Time to Buy and Sell Stock II
Say you have an array for whichthe ith elementis the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may completeas many transactions as you like (ie, buy one and sell one share of the stockmultiple times). However, you may not engage in multiple transactions at thesame time (ie, you must sell the stock before you buy again).
Example:
Input: [7, 1, 5,3, 6, 4]
Output: 7
Input: [7, 6, 4,3, 1]
Output: 0
Answer:
since we can do many transaction as we want, then we just need find every close valley and peak in the curve.
1 | func MaxprofileWithMultitransaction(prices []int) int { |
3.Best Time to Buy and Sell Stock III
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).
Answer:
DP problem, prof[i] is the max profile with up to r transactions before time i.
m = max profile with up to r-1 transaction and prices[i] as buying price in the next transaction at time i
prof[i] = max(prof[i-1],prices[i]+m)
1 | if prices == nil || len(prices) <= 0 { |
4.Best Time to Buy and Sell Stock IV
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 k transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
Answer:
DP problem
1 | prof[r][i] = max(prof[r][i-1],prices[i]+m) // max(profile with no transaction at time i,profile with transaction at time i) |
代码
1 | // MaxProfitWithKTransactionDP 动态规划版本 |