Find the contiguous subarray within an array (containing at least one number) which has the largest product.
For example, given the array [2,3,-2,4]
,
the contiguous subarray [2,3]
has the largest product = 6
.
Keep three pointers, one always points to current minimum number, one always points to current maximum number, one keeps on updating max result.
int maximumProduct(vector<int>& nums) {
int positive_max_so_far = 1;
int negative_min_so_far = 1;
int maxProduct = INT_MIN;
for(int i = 0; i < nums.size(); ++i) {
if(nums[i] == 0) {
positive_max_so_far = 1;
negative_min_so_far = 1;
} else if(nums[i] > 0) {
positive_max_so_far = positive_max_so_far * nums[i];
negative_min_so_far = min(negative_min_so_far, min(negative_min_so_far * nums[i], 1));
} else {
int tmp = negative_min_so_far;
negative_min_so_far = min(positive_max_so_far * nums[i], 1);
positive_max_so_far = max(tmp * nums[i], 1);
}
maxProduct = max(maxProduct, positive_max_so_far);
}
return maxProduct;
}
int main(void) {
vector<int> nums{-1, 2, 3, -2};
cout << maximumProduct(nums) << endl;
}
To summarize the algorithm, this is using Kadane's algorithm, optimized local --> optimized global.
1: Given an array of integer, Find the maximum sum subsequence such that elements are not consecutive.
For example: A[-2, 1, -3, 4, -1, 2, -5, 4], then max sum = 11 with the subarray [1, 4, 2, 4]
To use local optimized result to get optimized global results. In this function, we need to maintain two variables: contains(i), exclude(i)
int getMaxSum(vector<int>& nums) {
int n = nums.size();
vector<int> max_include(n, 0);
vector<int> max_exclude(n, 0);
max_include[0] = nums[0];
max_exclude[0] = INT_MIN;
int maxSum = nums[0];
for(int i = 1; i < nums.size(); ++i) {
max_include[i] = max(max_exclude[i-1] + nums[i], nums[i]);
max_exclude[i] = max(max_include[i-1], max_exclude[i-1]);
maxSum = max(max_include[i], max_exclude[i]);
}
return maxSum;
}
int main(void) {
vector<int> nums {-2, 1, -3, 4, -1, 2, 1, -5, 4};
cout << getMaxSum(nums) << endl;
}
Constraints: 1 <= N <= 2 ^ 100000, 0 <= L <= R < logN, Sample Input : 146, Sample output: 6
146 can be represented as 1 0 0 1 0 0 1 0, we can get a maximum of 6 ones in the given binary array by performing the following single segment bit flip operation:
Flip [1, 5] ==> 1 1 1 0 1 1 1 0