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

Commit 318f810

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

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package dynamic_programming;
2+
3+
/**
4+
* @author liangqian0723@gmail.com
5+
* @since 2020/3/9 10:33 AM
6+
*/
7+
public class LC_121_BestTimeToBuyOrSellStock {
8+
/**
9+
* 暴力遍历
10+
*/
11+
public int maxProfit(int[] prices) {
12+
int maxProfit = 0;
13+
for (int i = 0; i < prices.length - 1; i++) {
14+
for (int j = i + 1; j < prices.length; j++) {
15+
maxProfit = Math.max(maxProfit, prices[j] - prices[i]);
16+
}
17+
}
18+
return maxProfit;
19+
}
20+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package dynamic_programming;
2+
3+
import org.junit.Test;
4+
5+
import static org.hamcrest.core.Is.is;
6+
import static org.junit.Assert.assertThat;
7+
8+
/**
9+
* @author liangqian0723@gmail.com
10+
* @since 2020/3/9 10:28 AM
11+
*/
12+
public class LC_121_BestTimeToBuyOrSellStockTest {
13+
@Test
14+
public void best_time_to_buy_sell_stock_test() {
15+
LC_121_BestTimeToBuyOrSellStock bt = new LC_121_BestTimeToBuyOrSellStock();
16+
assertThat(bt.maxProfit(new int[]{7, 1, 5, 3, 6, 4}), is(5));
17+
}
18+
}

0 commit comments

Comments
 (0)