Brute Force
Intuition
Check every possible contiguous subarray by using two nested loops. For each starting index, extend the subarray one element at a time while maintaining the running product. Track the maximum product seen across all subarrays. This approach is straightforward but becomes slow for large inputs.
Algorithm
- Initialize maxProd to the smallest possible integer value.
- For each starting index i, initialize a running product to 1.
- For each ending index j from i to n-1, multiply the running product by nums[j].
- Update maxProd if the running product is larger.
- Return maxProd.
O(n^2)SpaceO(1)Code (C++ · Java · Python · Go)
class Solution {
public:
int maxProduct(vector<int>& nums) {
int maxProd = INT_MIN;
for (int i = 0; i < nums.size(); i++) {
int product = 1;
for (int j = i; j < nums.size(); j++) {
product *= nums[j];
maxProd = max(maxProd, product);
}
}
return maxProd;
}
};class Solution {
public int maxProduct(int[] nums) {
int maxProd = Integer.MIN_VALUE;
for (int i = 0; i < nums.length; i++) {
int product = 1;
for (int j = i; j < nums.length; j++) {
product *= nums[j];
maxProd = Math.max(maxProd, product);
}
}
return maxProd;
}
}def maxProduct(nums: list[int]) -> int:
max_prod = float('-inf')
for i in range(len(nums)):
product = 1
for j in range(i, len(nums)):
product *= nums[j]
max_prod = max(max_prod, product)
return max_prodfunc maxProduct(nums []int) int {
maxProd := nums[0]
for i := 0; i < len(nums); i++ {
product := 1
for j := i; j < len(nums); j++ {
product *= nums[j]
if product > maxProd {
maxProd = product
}
}
}
return maxProd
}