https://leetcode.com/problems/maximum-product-subarray/
Example 1:
Input: nums = [2,3,-2,4] Output: 6 Explanation: [2,3] has the largest product 6.
package pep.Day62;
public class LeetCode_152_Maximum_Product_Subarray {
public static void main(String[] args) {
int[] arr = new int[]{-2, 1, 0, 3, 4, -1, 6, -2};
System.out.print(maxProduct(arr));
}
public static int maxProduct(int[] nums) {
int ans = Integer.MIN_VALUE;
int product = 1;
// pehle left boundary se start krenge
for (int i = 0; i < nums.length; i++) {
product *= nums[i];
ans = Math.max(ans, product);
if (product == 0) {
product = 1;
}
}
// right boundary se start krenge
product = 1;
for (int i = nums.length - 1; i >= 0; i--) {
product *= nums[i];
ans = Math.max(ans, product);
if (product == 0) {
product = 1;
}
}
return ans;
}
}





No comments:
Post a Comment