Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 8406313

Browse files
committed
#121 股票买卖(只允许交易一次求最大收益)
1 parent 318f810 commit 8406313

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

main/src/dynamic_programming/LC_121_BestTimeToBuyOrSellStock.java

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ public class LC_121_BestTimeToBuyOrSellStock {
88
/**
99
* 暴力遍历
1010
*/
11-
public int maxProfit(int[] prices) {
11+
public int maxProfit_2d(int[] prices) {
1212
int maxProfit = 0;
1313
for (int i = 0; i < prices.length - 1; i++) {
1414
for (int j = i + 1; j < prices.length; j++) {
@@ -17,4 +17,17 @@ public int maxProfit(int[] prices) {
1717
}
1818
return maxProfit;
1919
}
20+
21+
public int maxProfit_1d(int[] prices) {
22+
int min = Integer.MAX_VALUE;
23+
int maxProfit = 0;
24+
for (int price : prices) {
25+
if (price > min) {
26+
maxProfit = Math.max(maxProfit, price - min);
27+
} else {
28+
min = price;
29+
}
30+
}
31+
return maxProfit;
32+
}
2033
}

main/test/dynamic_programming/LC_121_BestTimeToBuyOrSellStockTest.java

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,14 @@
1111
*/
1212
public class LC_121_BestTimeToBuyOrSellStockTest {
1313
@Test
14-
public void best_time_to_buy_sell_stock_test() {
14+
public void best_time_to_buy_sell_stock_resolve_2D_test() {
1515
LC_121_BestTimeToBuyOrSellStock bt = new LC_121_BestTimeToBuyOrSellStock();
16-
assertThat(bt.maxProfit(new int[]{7, 1, 5, 3, 6, 4}), is(5));
16+
assertThat(bt.maxProfit_2d(new int[]{7, 1, 5, 3, 6, 4}), is(5));
17+
}
18+
19+
@Test
20+
public void best_time_to_buy_sell_stock_resolve_1D_test() {
21+
LC_121_BestTimeToBuyOrSellStock bt = new LC_121_BestTimeToBuyOrSellStock();
22+
assertThat(bt.maxProfit_1d(new int[]{7, 1, 5, 3, 6, 4}), is(5));
1723
}
1824
}

0 commit comments

Comments
 (0)