FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

Add: Max Profit · OmarShawky1/Problem-Solving-Map@1cc3159 · GitHub

Commit 1cc3159

Browse files
committed
Add: Max Profit
1 parent f44adb9 commit 1cc3159

1 file changed

Lines changed: 34 additions & 0 deletions

File tree

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package arrays.slidingWindow;
2+
3+
public class MaxProfit {
4+
public int maxProfit1(int[] prices) {
5+
int prof = 0, min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
6+
7+
for (int price : prices) {
8+
if (price < min) {
9+
min = price;
10+
max = Integer.MIN_VALUE; // Reset value
11+
} else {
12+
max = Math.max(max, price);
13+
prof = Math.max(prof, max - min);
14+
}
15+
}
16+
return prof;
17+
}
18+
19+
public int maxProfit(int[] prices) {
20+
int prof = 0, max = prices[prices.length - 1];
21+
for (int i = prices.length - 2; i >= 0; i--) {
22+
prof = Math.max(prof, max - prices[i]);
23+
max = Math.max(max, prices[i]);
24+
}
25+
return prof;
26+
}
27+
28+
public static void test() {
29+
MaxProfit m = new MaxProfit();
30+
assert m.maxProfit(new int[]{7, 1, 5, 3, 6, 4}) == 5;
31+
assert m.maxProfit(new int[]{7, 6, 4, 3, 1}) == 0;
32+
assert m.maxProfit(new int[]{3,2,6,5,0,3}) == 4;
33+
}
34+
}

0 commit comments

Comments
 (0)

Back | FazBrowse Home | New Git URL