Skip to content

Commit d38e8d2

Browse files
committed
188 (1)
1 parent 243258b commit d38e8d2

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* Time : O() ; Space: O()
3+
* @tag : Dynamic Programming
4+
* @by : Steven Cooks
5+
* @date: Sep 30, 2015
6+
***************************************************************************
7+
* Description:
8+
*
9+
* Say you have an array for which the ith element is the price of a given stock on day i.
10+
*
11+
* Design an algorithm to find the maximum profit. You may complete at most k transactions.
12+
*
13+
* Note: You may not engage in multiple transactions at the same time
14+
* (ie, you must sell the stock before you buy again).
15+
*
16+
***************************************************************************
17+
* {@link https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/ }
18+
* @reference {@link https://leetcode.com/discuss/15153/a-clean-dp-solution-which-generalizes-to-k-transactions }
19+
*/
20+
package _188_BestTimeToBuyAndSellStockIV;
21+
22+
/** see test {@link _188_BestTimeToBuyAndSellStockIV.SolutionTest } */
23+
public class Solution {
24+
25+
public int maxProfit(int k, int[] prices) {
26+
int n = prices.length;
27+
int[][] f = new int[k + 1][n];
28+
for (int i = 0; i < k; i++) {
29+
int tmpMax = f[k - 1][0] - prices[0];
30+
for (int j = 1; j < n; j++) {
31+
f[i][j] = Math.max(f[i][j - 1], prices[j] + tmpMax);
32+
tmpMax = Math.max(tmpMax, f[i - 1][j] - prices[j]);
33+
}
34+
}
35+
return k;
36+
}
37+
38+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy