- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem121.java
More file actions
Latest commit
31 lines (28 loc) · 901 Bytes
/
Copy pathProblem121.java
File metadata and controls
31 lines (28 loc) · 901 Bytes
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
classProblem121 {
publicstaticvoidmain(String[] args) {
Problem121p = newProblem121();
int[] nums = {1,4,2};
System.out.println(p.maxProfit(nums));
}
publicintmaxProfit1(int[] prices) {
intmax = Integer.MIN_VALUE;
for (inti = prices.length-1; i > 0; i--) {
for (intj = i-1; j >= 0; j--) {
intprofit = prices[i]-prices[j];
max = profit > max ? profit: max;
}
}
returnmax;
}
publicintmaxProfit(int[] prices) {
intminprice = Integer.MAX_VALUE;
intmaxprofit = 0;
for (inti = 0; i < prices.length; i++) {
if (prices[i] < minprice)
minprice = prices[i];
elseif (prices[i] - minprice > maxprofit)
maxprofit = prices[i] - minprice;
}
returnmaxprofit;
}
}