-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC0121BuyAndSellStockJava.java
More file actions
52 lines (45 loc) · 1.4 KB
/
LC0121BuyAndSellStockJava.java
File metadata and controls
52 lines (45 loc) · 1.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package com.nphausg.leetcode.easy;
import com.nphausg.leetcode.config.BaseTest;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertEquals;
/**
* <a href="https://leetcode.com/problems/best-time-to-buy-and-sell-stock">121. Best Time to Buy and Sell Stock</a>
*/
@RunWith(Enclosed.class)
public class LC0121BuyAndSellStockJava {
// Brute-force
public static int maxProfit(int[] prices) {
int n = prices.length;
int max = 0;
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
int price = prices[j] - prices[i];
if (price > max) {
max = price;
}
}
}
return max;
}
public static int maxProfit2(int[] prices) {
int maxProfit = 0, minPrice = Integer.MAX_VALUE;
for (int price : prices) {
if (price < minPrice) {
minPrice = price;
} else {
int profit = price - minPrice;
if (profit > maxProfit) {
maxProfit = profit;
}
}
}
return maxProfit;
}
public static class TestCases extends BaseTest {
@org.junit.Test
public void testCases() {
assertEquals(5, maxProfit2(new int[]{7, 1, 5, 3, 6, 4}));
}
}
}