Date: 10-09-2025 Time: 19:12

class Solution {
public:
    int getMaxLen(vector<int>& nums) {
        int negCount = 0, zeroIndex = -1, firstNegIndex = -1, result = 0;
        
        for(int i = 0; i < nums.size(); i++) {
            if(nums[i] == 0) {
                // Zero resets the segment completely
                zeroIndex = i;
                negCount = 0;
                firstNegIndex = -1;  // ✅ Reset first negative too!
            }
            else {
                if(nums[i] < 0) {
                    negCount++;
                    if(negCount == 1)
                        firstNegIndex = i;  // Store first negative in new segment
                }
                
                if(negCount % 2 == 0)
                    // Even negatives: use entire segment after last zero
                    result = max(result, i - zeroIndex);
                else
                    // Odd negatives: exclude first negative
                    result = max(result, i - firstNegIndex);
            }
        }
        return result;
    }
};
 

WHY -1, Natural Length Calculation: i - (-1) = i + 1 gives correct length from start

When we calculate lengths:

  • i - zeroIndex where zeroIndex = -1i - (-1) = i + 1 ✅ (length from array start)
  • i - firstNegIndex where firstNegIndex = -1i - (-1) = i + 1 ✅ (length from segment start)