Question Link

https://leetcode.com/problems/maximum-product-subarray/

Question Description

Given an array, return the maximum product that can be computed from subarray.
Input: nums = [2,3,-2,4,-2]
Output: 96
Input: nums = [2,3,-2,4]
Output: 6
Input: nums = [-2,0,-1]
Output: 0

Simulation

Case1 :- All the elements are positive - return Product of all the elements in the array
Case2 :- Array have even number of negative elements - return
Case3 :- Array have odd number of negative elements.
Case4 :- Array also contains 0

Solution 1: Array Traversing

Maintaining Max, Min and Res Variable. The golbal max is computed with either Max or Min * (Negative Number)
Leetcode 152 Maximum Product Subarray - 图1

Solution 2: Array Traversing Optimized

Based on the above solution, we notices that when multiple negative number, we swap the min and max to avoid additional computation.

Solution 3: Two Pointers+ Prefix/Sufix

Leetcode 152 Maximum Product Subarray - 图2

Implementation

Solution 1: Array Traversing

  1. public int maxProduct(int[] nums) {
  2. int max = nums[0], min = nums[0], ans = nums[0];
  3. for (int i = 1; i < nums.length; i++) {
  4. int temp = max; // store the max because before updating min your max will already be updated
  5. max = Math.max(Math.max(max * nums[i], min * nums[i]), nums[i]);
  6. min = Math.min(Math.min(temp * nums[i], min * nums[i]), nums[i]);
  7. if (max > ans) {
  8. ans = max;
  9. }
  10. }
  11. return ans;
  12. }

Solution 2: Array Traversing Optimized

  1. public int maxProduct(int[] nums) {
  2. int max = nums[0], min = nums[0], ans = nums[0];
  3. int n = nums.length;
  4. for (int i = 1; i < n; i++) {
  5. // Swapping min and max
  6. if (nums[i] < 0) {
  7. int temp = max;
  8. max = min;
  9. min = temp;
  10. }
  11. max = Math.max(nums[i], max * nums[i]);
  12. min = Math.min(nums[i], min * nums[i]);
  13. ans = Math.max(ans, max);
  14. }
  15. return ans;
  16. }

Solution 3: Two Pointers + Prefix/Surfix

  1. public int maxProduct(int[] nums) {
  2. int n = nums.length;
  3. int l = 1, r = 1;
  4. int ans = nums[0];
  5. for (int i = 0; i < n; i++) {
  6. //if any of l or r become 0 then update it to 1
  7. l = l == 0 ? 1 : l;
  8. r = r == 0 ? 1 : r;
  9. l *= nums[i]; //prefix product
  10. r *= nums[n - 1 - i]; //suffix product
  11. ans = Math.max(ans, Math.max(l, r));
  12. }
  13. return ans;
  14. }