Topic Link: Click to open the link
Topic Information:
Find the contiguous subarray within an array (containing at least one number) which have the largest product.
for example, given the Array [2,3,-2,4" ,
the contiguous Subarray [2,3" has the largest product = 6 .
The idea of solving problems: the sum of the habit of the smallest string, suddenly comes a product of the smallest string, also very interesting.
There are two kinds of situations: there is no 0 in the character array, 0. Two cases.
(1) no 0 in character array
Character array, in fact, two, even number of negative numbers, odd number of negative numbers.
1, an even number of negative numbers, such as [-1 2 3-4 5], it is clear that the largest string is all.
2, an odd number of negative numbers, such as [-2 2 5-4-3], the largest string is the substring after the first negative [2 5-4-3].
So in summary, the maximum string is only two cases, one is the entire string, one is the first negative number after the string. So as long as the values in both cases are stored, the final result can be obtained by comparing them.
(2) There are 0 in the string
Before we can achieve this, we can implement the array after 0 as a new array. For example [5 6-5 0 2 3 8 9-5], you can think of the array after 0 as 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; }};Reprint Please specify Vanish_dust
Leetcode-maximum Product Subarray