|
| 1 | +/* |
| 2 | + * @lc app=leetcode id=188 lang=java |
| 3 | + * |
| 4 | + * [188] Best Time to Buy and Sell Stock IV |
| 5 | + * |
| 6 | + * https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/description/ |
| 7 | + * |
| 8 | + * algorithms |
| 9 | + * Hard (25.90%) |
| 10 | + * Total Accepted: 80.3K |
| 11 | + * Total Submissions: 309.9K |
| 12 | + * Testcase Example: '2\n[2,4,1]' |
| 13 | + * |
| 14 | + * Say you have an array for which the ith element is the price of a given |
| 15 | + * stock on day i. |
| 16 | + * |
| 17 | + * Design an algorithm to find the maximum profit. You may complete at most k |
| 18 | + * transactions. |
| 19 | + * |
| 20 | + * Note: |
| 21 | + * You may not engage in multiple transactions at the same time (ie, you must |
| 22 | + * sell the stock before you buy again). |
| 23 | + * |
| 24 | + * Example 1: |
| 25 | + * |
| 26 | + * |
| 27 | + * Input: [2,4,1], k = 2 |
| 28 | + * Output: 2 |
| 29 | + * Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit |
| 30 | + * = 4-2 = 2. |
| 31 | + * |
| 32 | + * |
| 33 | + * Example 2: |
| 34 | + * |
| 35 | + * |
| 36 | + * Input: [3,2,6,5,0,3], k = 2 |
| 37 | + * Output: 7 |
| 38 | + * Explanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit |
| 39 | + * = 6-2 = 4. |
| 40 | + * Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = |
| 41 | + * 3. |
| 42 | + * |
| 43 | + */ |
| 44 | +class Solution { |
| 45 | + public int maxProfit(int k, int[] prices) { |
| 46 | + int profit = 0; |
| 47 | + int n = prices.length; |
| 48 | + |
| 49 | + // 当 k 大于天数的一半时,基本可以等同于交易任意次 |
| 50 | + if (k >= n/2) { |
| 51 | + for (int i = 1; i < n; i++) { |
| 52 | + if (prices[i] > prices[i-1]) { |
| 53 | + profit += prices[i] - prices[i-1]; |
| 54 | + } |
| 55 | + } |
| 56 | + return profit; |
| 57 | + } |
| 58 | + |
| 59 | + int dp[][] = new int[k+1][n]; |
| 60 | + for (int i = 1; i <= k; i++) { |
| 61 | + int temp = -prices[0]; |
| 62 | + for (int j = 1; j < n; j++) { |
| 63 | + // 交易 i 次,第 j 天的最大收益 |
| 64 | + dp[i][j] = Math.max(dp[i][j-1], temp + prices[j]); |
| 65 | + // 交易 i 次,第 j 天买入股票时的最大收益 |
| 66 | + temp = Math.max(temp, dp[i-1][j-1] - prices[j]); |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + return dp[k][n-1]; |
| 71 | + } |
| 72 | +} |
| 73 | + |
0 commit comments