Skip to content

Latest commit

 

History

History
executable file
·
73 lines (64 loc) · 2.41 KB

188. Best Time to Buy and Sell Stock IV.md

File metadata and controls

executable file
·
73 lines (64 loc) · 2.41 KB

188. Best Time to Buy and Sell Stock IV

Question

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).

Example 1:

Input: [2,4,1], k = 2
Output: 2
Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.

Example 2:

Input: [3,2,6,5,0,3], k = 2
Output: 7
Explanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4.
             Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.

Solution

  • Method 1: dp
    1. We need to pay attention to the initialization.
    2. Transaction function is same as 123. Best Time to Buy and Sell Stock III.
    3. If k is larger than prices length, we treat it as question 122. Best Time to Buy and Sell Stock II.
     class Solution {
     	public int maxProfit(int k, int[] prices) {
     		if(k == 0 || prices == null || prices.length <= 1) return 0;
     		int len = prices.length;
     		if(k > len) return maxProfit(prices);
     		int[][] buys = new int[len + 1][k + 1];
     		int[][] sells = new int[len + 1][k + 1];
     		for(int i = 2; i <= k; i++){
     			for(int j = 0; j < i; j++){
     				buys[j][i] = Integer.MIN_VALUE;
     			}
     		}
     		int sum = 0;
     		for(int i = 1; i <= k; i++){
     			sum -= prices[i - 1];
     			buys[i][i] = sum;
     		}
     		for(int i = 2; i <= len; i++){
     			for(int j = 1; j <= k; j++){
     				buys[i][j] = Math.max(buys[i - 1][j], sells[i - 1][j - 1] - prices[i - 1]);
     				sells[i][j] = Math.max(sells[i - 1][j], buys[i - 1][j] + prices[i - 1]);
     			}
     		}        
     		int profit = 0;
     		for(int i = 0; i <= k; i++){
     			profit = Math.max(profit, sells[len][i]);
     		}
     		return profit;
     	}
     	
     	private int maxProfit(int[] prices) {
     			int len = prices.length;
     			int[] buys = new int[len + 1];
     			int[] sells = new int[len + 1];
     			buys[1] = -prices[0];
     			for(int i = 2; i <= len; i++){
     				buys[i] = Math.max(buys[i - 1], sells[i - 1] - prices[i - 1]);
     				sells[i] = Math.max(sells[i - 1], buys[i - 1] + prices[i - 1]);
     			}
     			return sells[len];
     		}
     }