~/coding-interview/leetcode-solution-max-length-positive-product.md

Maximum Length of Subarray With Positive Product - Leet Code Solution

// TL;DR

Track both the longest positive-product and longest negative-product subarray lengths. A negative number swaps them. Zero resets both to 0.

Maximum Length of Subarray With Positive Product - Leet Code Solution

Problem Statement

Maximum Length of Subarray With Positive Product.

Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.

A subarray of an array is a consecutive sequence of zero or more values taken out of that array.

Return the maximum length of a subarray with positive product.

Example

Input: nums = [1,-2,-3,4]
Output: 4

Input: nums = [0,1,-2,-3,-4]
Output: 3

Note: You can include value 0 in your range as this will make product zero.

Solution

Note: We don’t have to include value-0 in our result. This adds to additional complexity to problem.

Lets think of sliding window kind of solution where we keep track of some indexes and calculate the result.

Few things to keep in mind:

  • You can not leave a negative number as it is.
    As multiplication of two negative numbers is positive
  • You don’t need to actually multiply numbers. The question is about maximum subarray length which multiplies to a positive result.
  • You just need to keep a track of how many numbers multiplies to a positive result.
  • If your negative counts becomes odd, you would want to remove a negative number from your range.

Lets talk about some helper variables

Lets talk about some of the variables we will need in this problem.

Negative Count
You need a variable to keep the count the negatives till your iterator index.

Index of Zero
You will need an index of when you last found a zero.

Index of first negative number
This will be required in case you encountered negative count to be odd. You would want to calculate length of array excluding first negative number.

Code

Alright, lets look at the code.

public int getMaxLen(int[] nums) {
   int max = 0;
   
   int firstNegativeIndex = -1;
   int negativeCount = 0;
   
   int zeroIndex = -1;
   
   for (int i=0; i<nums.length; i++) {
      //{-1,-2,-3,0,1};
      if (nums[i] < 0) {
         negativeCount ++;
         //update firstNegativeIndex for first time
         if (firstNegativeIndex == -1) {
            firstNegativeIndex = i;
         } 
         else {
            //if its a negative number and count becomes even
            if (negativeCount % 2 == 0) {
               max = Math.max(max, i-zeroIndex);
            }
         }
      }
      else if (nums[i] == 0) {
         //reset everything
         firstNegativeIndex = -1;
         negativeCount = 0;
         zeroIndex = i;
      }
      else {
         if (negativeCount % 2 == 0) {
            max = Math.max(max, i-zeroIndex);
         }
         else {
            max = Math.max(max, i-firstNegativeIndex);
         }
      }
   }
   
   return max;
}

Complexity

Its O(n)

$ subscribe --weekly

One deep dive a week, in your inbox

System design, AI engineering, trading systems and interview prep. Tested code, real numbers. Free, and you can unsubscribe any time.

or read it on gyanbyte.substack.com

Share

Related Posts

Replace all spaces in a string with %20

Replace all spaces in a string with %20

Problem Statement Replace all spaces in a string with ‘%20’ (three characters…

Valid Palindrome - Leet Code Solution

Valid Palindrome - Leet Code Solution

Problem Statement Given a string, determine if it is a palindrome, considering…

Valid Anagrams - Leet Code Solution

Valid Anagrams - Leet Code Solution

Problem Statement Given two strings s and t , write a function to determine if t…

Rotate Image - Leet Code Solution

Rotate Image - Leet Code Solution

Problem Statement You are given an n x n 2D matrix representing an image, rotate…

Validate Sudoku - Leet Code Solution

Validate Sudoku - Leet Code Solution

Problem Statement Determine if a 9x9 Sudoku board is valid. Only the filled…

Plus One - Leet Code Solution

Plus One - Leet Code Solution

Problem Statement Given a non-empty array of digits representing a non-negative…

Latest Posts

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

In the previous article I argued that AI is not killing software engineering…

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

A few months back I approved a PR that was almost entirely AI-generated. It…

How to Debug AI-Generated Code: Understand First, Fix Last

How to Debug AI-Generated Code: Understand First, Fix Last

In the last article I wrote about reviewing AI code before it goes in. This one…

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

Every few weeks somebody sends me a scary headline — “AI will replace all…

The Transactional Outbox Pattern: Never Lose an Event Again

The Transactional Outbox Pattern: Never Lose an Event Again

This is one of those patterns that looks like nothing until you get burnt once…

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Here is a question I like to ask in interviews: your bank account shows a…