Skip to content

Commit 3acdff1

Browse files
solves maximum product sub array in java
1 parent ddf8758 commit 3acdff1

File tree

3 files changed

+29
-2
lines changed

3 files changed

+29
-2
lines changed

Diff for: README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,7 @@
135135
| 148 | [Sort List](https://leetcode.com/problems/sort-list) | [![Java](assets/java.png)](src/SortList.java) | |
136136
| 150 | [Evaluate Reverse Polish Notation](https://leetcode.com/problems/evaluate-reverse-polish-notation) | [![Java](assets/java.png)](src/EvaluateReversePolishNotation.java) | |
137137
| 151 | [Reverse Words in a String](https://leetcode.com/problems/reverse-words-in-a-string) | [![Java](assets/java.png)](src/ReverseWordsInAString.java) | |
138-
| 152 | [Maximum Product Subarray](https://leetcode.com/problems/maximum-product-subarray) | | |
138+
| 152 | [Maximum Product Subarray](https://leetcode.com/problems/maximum-product-subarray) | [![Java](assets/java.png)](src/MaximumProductSubarray.java) | |
139139
| 153 | [Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array) | | |
140140
| 155 | [Min Stack](https://leetcode.com/problems/min-stack) | [![Java](assets/java.png)](src/MinStack.java) [![Python](assets/python.png)](python/min_stack.py) | |
141141
| 156 | 🔒 [Binary Tree Upside Down](https://leetcode.com/problems/binary-tree-upside-down) | | |

Diff for: src/HelloWorld.java

+3-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
public class HelloWorld {
22
public static void main(String[] args) {
3-
System.out.println(ReverseWordsInAString.reverseWords(" hello world "));
3+
System.out.println(
4+
MaximumProductSubarray.maxProduct(new int[] {-4, -3, -2})
5+
);
46
}
57
}

Diff for: src/MaximumProductSubarray.java

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// https://leetcode.com/problems/maximum-product-subarray
2+
// T: O(N)
3+
// S: O(1)
4+
5+
public class MaximumProductSubarray {
6+
public static int maxProduct(int[] nums) {
7+
int max = nums[0], min = nums[0], maxSoFar = max, temp;
8+
for (int i = 1 ; i < nums.length ; i++) {
9+
int number = nums[i];
10+
temp = max(max * number, min * number, number);
11+
min = min(max * number, min * number, number);
12+
max = temp;
13+
maxSoFar = Math.max(maxSoFar, max);
14+
}
15+
return maxSoFar;
16+
}
17+
18+
private static int max(int a, int b, int c) {
19+
return Math.max(a, Math.max(b, c));
20+
}
21+
22+
private static int min(int a, int b, int c) {
23+
return Math.min(a, Math.min(b, c));
24+
}
25+
}

0 commit comments

Comments
 (0)