Skip to content

Commit 34d2e4e

Browse files
committed
fix: prevent integer overflow in MaximumProductSubarray using long type
1 parent dfa04d6 commit 34d2e4e

File tree

1 file changed

+5
-5
lines changed

1 file changed

+5
-5
lines changed

src/main/java/com/thealgorithms/dynamicprogramming/MaximumProductSubarray.java

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -33,14 +33,14 @@ public static int maxProduct(int[] nums) {
3333
return 0;
3434
}
3535

36-
int maxProduct = nums[0];
37-
int currentMax = nums[0];
38-
int currentMin = nums[0];
36+
long maxProduct = nums[0];
37+
long currentMax = nums[0];
38+
long currentMin = nums[0];
3939

4040
for (int i = 1; i < nums.length; i++) {
4141
// Swap currentMax and currentMin if current number is negative
4242
if (nums[i] < 0) {
43-
int temp = currentMax;
43+
long temp = currentMax;
4444
currentMax = currentMin;
4545
currentMin = temp;
4646
}
@@ -53,6 +53,6 @@ public static int maxProduct(int[] nums) {
5353
maxProduct = Math.max(maxProduct, currentMax);
5454
}
5555

56-
return maxProduct;
56+
return (int) maxProduct;
5757
}
5858
}

0 commit comments

Comments
 (0)