Maximum Product Subarray
Problem
Find the contiguous part (subarray) with the largest product. Print that product. The array can have negative numbers and zeros.
Constraints
- 1 <= n <= 100
- |a[i]| <= 10
- the product fits in long and in 2^53
Examples
Input
4 2 3 -2 4
Output
6
Solutions
Kadane's idea for products needs two running values: a very negative product times a negative number becomes very positive. Zero resets both values through the 'value alone' option.
/*
* Problem : Process an array.
* Input : n, then n integers.
* Output : The largest product.
* Approach: Track max and min.
* Time : O(n)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static long solve(int[] a) {
// Step 1: Keep the biggest and the smallest product of a subarray that ends at the current element.
// The smallest product matters because a negative number can turn it into the biggest.
long best = a[0];
long maxEnding = a[0];
long minEnding = a[0];
for (int i = 1; i < a.length; i++) {
long value = a[i];
// Step 2: The new products come from the value alone, or the value times the old biggest or smallest.
long first = maxEnding * value;
long second = minEnding * value;
maxEnding = Math.max(value, Math.max(first, second));
minEnding = Math.min(value, Math.min(first, second));
// Step 3: Keep the best result seen so far.
best = Math.max(best, maxEnding);
}
return best;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = scanner.nextInt();
}
System.out.println(solve(a));
}
}
Hints (1)
- Why do we also track the smallest product?