Similar Problems

Similar Problems not available

Maximum Score Of A Good Subarray - Leetcode Solution


LeetCode:  Maximum Score Of A Good Subarray Leetcode Solution

Difficulty: Hard

Topics: stack binary-search array two-pointers  

Problem Statement:

Given an array of integers nums, a good subarray is a contiguous subarray of nums containing no more than one unique value.

Return the maximum number of good subarrays of nums.


We can solve this problem using the sliding window technique.

We will initialize three pointers: left, right, and uniqueCount.

uniqueCount will keep track of the number of unique integers in the current subarray.

Initially, left and right will both be at the 0th index of the array and uniqueCount will be 1.

We will then iterate through the array using the right pointer and incrementing uniqueCount if we encounter a new integer.

If uniqueCount becomes more than 2, we will increment the left pointer and decrement uniqueCount if the integer that left pointer is pointing to is not present in the rest of the subarray.

At every step of the iteration, we will calculate the length of the current subarray and add it to a sum variable.

We will then return the sum variable.

Below is the implementation of this algorithm:

class Solution:
    def maxGoodSubarrays(self, nums: List[int]) -> int:
        left = right = good_subarrays = unique_count = 0
        while right < len(nums):
            if nums[right] not in nums[left:right]:
                unique_count += 1
            while unique_count > 1:
                if nums[left] not in nums[left+1:right]:
                    unique_count -= 1
                left += 1
            good_subarrays += right - left + 1
            right += 1        
        return good_subarrays

Time Complexity:

The above algorithm has a time complexity of O(n) as it just iterates over the array once.

Space Complexity:

The space complexity of the algorithm is O(1) as we only use constant extra space.


Input: nums = [1,2,1,3,1] Output: 4 Explanation: There are 4 good subarrays: [1], [2], [1,2,1], [1,3,1].


In this problem, we used the sliding window technique to solve the problem in linear time complexity. We initialized three pointers and iterated over the array while updating the pointers and keeping track of the count of good subarrays. This is a good example of how the sliding window technique can be used to solve a problem efficiently.

Maximum Score Of A Good Subarray Solution Code