LeetCode-Maximum Product Subarray, maximumsubarray
Question link: Click the open link
Question information:
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.
Solution: It's interesting to get used to the sum of the smallest strings.
There are two cases: There is no 0 in the character array and there is 0. In either case.
(1) No 0 characters in the character array
In the character array, there are actually two types: an even number and an odd number.
1, an even number of negative numbers, for example, [-1 2 3-4 5]. Obviously, the largest string is all.
2. an odd number, for example, [-2 2 5-4-3]. The largest string is the substring following the first negative number [2 5-4-3].
To sum up, there are only two cases for the maximum string: one is all strings and the other is strings after the first negative number. Therefore, you only need to store the values in these two cases and then compare them to get the final result.
(2) The string contains 0
We can implement the array after 0 as a new array. For example, [5 6-5 0 2 3 8 9-5], you can convert the array after 0 into a new array.
[2 3 8 9-5];
Code:
class Solution {public: int maxProduct(int A[], int n) { int preNum1 = 1; //Remember all the Numbers int preNum2 = 1; //Remember all the Behind Numbers of first negative bool start2; int answers ; if(n == 0) return 0; if(n > 0) answers = A[0]; int negSum = 0; for(size_t i = 0; i != n;i++) { preNum1 *= A[i]; //cout<<"preNum1="<<preNum1<<endl; answers = (preNum1 > answers? preNum1:answers); if(start2 == true) { preNum2 *= A[i]; //cout<<"preNum2="<<preNum2<<endl; answers = (preNum2 > answers? preNum2:answers); } if(A[i] < 0) { negSum ++; } if(negSum == 1 && start2 == false) { start2 = true; preNum2 = 1; } if(A[i] == 0) { answers = (answers > 0) ? answers : 0; preNum1 = 1; preNum2 = 1; negSum = 0; start2 = false; } } return answers; }};Reprinted by vanish_dust