← Home

1567. Maximum Length of Subarray With Positive Product

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
greedyC++Markdown
156

Let's make this one less mysterious. For 1567. Maximum Length of Subarray With Positive Product, the solution in this repository is mainly a greedy solution.

Guide

What?

Before optimizing anything, pin down what information is still useful after each move. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: greedy.

The notes already sitting in the source point us in the right direction:

  • time: O(N)

Guide

When?

Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are getMaxLen.

Guide

Why?

The solution works because it narrows the problem until every update has a clear reason to exist.

  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(N)
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Runtime: 252 ms, faster than 40.00% of C++ online submissions for Maximum Length of Subarray With Positive Product.
02//Memory Usage: 58.7 MB, less than 20.00% of C++ online submissions for Maximum Length of Subarray With Positive Product.
03//time: O(N)
04class Solution {
05public:
06    int getMaxLen(vector<int>& nums) {
07        int n = nums.size();
08        int neg = 0;
09        int len = 0;
10        int ans = 0;
11        vector<int> negs;
12        
13        int i = 0;
14        while(i < n){
15            /*
16            for a specific start point "i", 
17            records the position of negative numbers until a "0"
18            */
19            int j;
20            for(j = i; j < n && nums[j] != 0; ++j){
21                if(nums[j] < 0){
22                    negs.push_back(j);
23                }
24            }
25            
26            // cout << "negs: " << negs.size() << endl;
27            
28            if(negs.size() % 2 == 0){
29                /*
30                if we have even number of negative numbers,
31                then the subarray nums[i...j-1] is valid
32                */
33                len = j-i;
34            }else if(negs.size() == 1){
35                // cout << negs[0]-i << " or " << j-1-(negs[0]+1)+1 << endl;
36                /*
37                if there is a negative number in nums[i...j-1],
38                then we may choose [i...negs[0]-1] or [negs[0]+1...j-1]
39                */
40                len = max(negs[0]-i, j-1-(negs[0]+1)+1);
41            }else{
42                /*
43                there are multiple negative numbers,
44                we may exclude the first one or the last one,
45                so [i...last-1] or [first+1...j-1]
46                */
47                int first = negs[0], last = negs.back();
48                // cout << last-i << " or " << j-1-(first+1)+1 << endl;
49                len = max(last-i, j-1-(first+1)+1);
50            }
51            
52            ans = max(ans, len);
53            negs.clear();
54            
55            //next start from the position behind "0"
56            i = j+1;
57        }
58        
59        ans = max(ans, len);
60        
61        return ans;
62    }
63};
64
65//Greedy
66//https://leetcode.com/problems/maximum-length-of-subarray-with-positive-product/discuss/819278/Java-O(n)-time-O(1)-space
67//Runtime: 260 ms, faster than 20.00% of C++ online submissions for Maximum Length of Subarray With Positive Product.
68//Memory Usage: 57.9 MB, less than 20.00% of C++ online submissions for Maximum Length of Subarray With Positive Product.
69class Solution {
70public:
71    int getMaxLen(vector<int>& nums) {
72        int firstNeg = -1, lastZero = -1;
73        int negCount = 0;
74        int ans = 0;
75        
76        int n = nums.size();
77        
78        for(int i = 0; i < n; ++i){
79            int e = nums[i];
80            
81            if(e < 0){
82                ++negCount;
83                if(firstNeg == -1)
84                    firstNeg = i;
85            }
86            
87            if(e == 0){
88                lastZero = i;
89                negCount = 0;
90                //this also need to be reset!
91                firstNeg = -1;
92            }else{
93                //e > 0 or e < 0!!
94                if(!(negCount&1)){
95                    //negCount is even
96                    //[lastZero+1...i]
97                    // cout << i << " : " << i-lastZero << endl;
98                    ans = max(ans, i-lastZero);
99                }else{
100                    //[firstNeg+1...i]
101                    // cout << i << " : " << i-firstNeg << endl;
102                    ans = max(ans, i-firstNeg);
103                }
104            }
105        }
106        
107        return ans;
108    }
109};

Cost

Complexity

Time
O(N)
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.