-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaximizeProfit.java
More file actions
27 lines (23 loc) · 845 Bytes
/
MaximizeProfit.java
File metadata and controls
27 lines (23 loc) · 845 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
public class MaximizeProfit {
public static int maximizeProfit(int[] prices) {
int n = prices.length;
if (n == 0) return 0;
int minPrice = Integer.MAX_VALUE;
int maxProfit = 0;
for (int i = 0; i < n; i++) {
if (prices[i] < minPrice) {
minPrice = prices[i];
} else {
int profit = prices[i] - minPrice;
maxProfit = Math.max(maxProfit, profit);
}
}
return maxProfit;
}
public static void main(String[] args) {
int[] prices1 = {2, 3, 5};
int[] prices2 = {8, 5, 1};
System.out.println("Maximum Profit (Example 1): " + maximizeProfit(prices1));
System.out.println("Maximum Profit (Example 2): " + maximizeProfit(prices2));
}
}