Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitd38e8d2

Browse files
committed
188 (1)
1 parent243258b commitd38e8d2

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+
publicclassSolution {
24+
25+
publicintmaxProfit(intk,int[]prices) {
26+
intn =prices.length;
27+
int[][]f =newint[k +1][n];
28+
for (inti =0;i <k;i++) {
29+
inttmpMax =f[k -1][0] -prices[0];
30+
for (intj =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+
returnk;
36+
}
37+
38+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp