L20 - Max Product Subarray
L20 - Max Product Subarray
Introduction
✔ Given an array that contains both positive and
negative integers, the task is to find the product of the
maximum product sub array.
✔ Subsequence: A subsequence is a sequence that can
be derived from another sequence by zero or more
elements, without changing the order of the
remaining elements.
✔ Sub array: A sub array is a contiguous part of array. An
array that is inside another array.
A Subsequence cannot be a sub array
✔ For instance, let arr = [1,2,3,4,5]
✔ Examples for Subarrays: [1], [1,2], [2,3,4] etc
✔ Examples for Subsequences: [1], [1,3], [1,2,3], [2,3,4]
Maximum Product Subarray by Traverse Over Every
Contiguous Subarray:
// Driver Code
public static void main(String[] args)
{
int arr[] = { 1, -2, -3, 0, 7, -8, -2 };
System.out.println("Maximum Sub array product is "
+
maxSubarrayProduct(arr));
}
}
Output : Maximum Sub array product is 112
✔ The idea is to use Kadane’s algorithm and maintain 3 variables max_so_far, max_ending_here
& min_ending_here. Iterate the indices 0 to N-1 and update the variables such that.
✔ update the max_so_far with the maximum value for each index.
return max_so_far;
}
// Driver code
public static void main(String args[])
{
int[] arr = { 1, -2, -3, 0, 7, -8, -2 };
int n = arr.length;
System.out.printf("Maximum Sub array product is %d",
THANK YOU