Program to find maximum score of a good subarray in Python

Suppose we have an array called nums and a value k. The score of a subarray (i, j) is defined as the minimum value in subarray nums[i..j] multiplied by its length (j-i+1). A good subarray is one where i <= k <= j (meaning it must include index k). We need to find the maximum possible score among all good subarrays.

So, if the input is like nums = [2,5,4,8,5,6] and k = 3, then the output will be 20 because the optimal subarray is (1, 5), where the minimum of nums[1..5] is 4, so 4*(5-1+1) = 20.

Algorithm

To solve this problem, we will use a two-pointer approach expanding from index k ?

  • Initialize ans and minNum with nums[k]

  • Set pointers i and j both to k

  • Expand the subarray in both directions while maintaining the minimum value

  • Calculate the score for each valid subarray and track the maximum

  • Update the minimum value as we expand

Example

Let us see the following implementation to get a better understanding ?

def solve(nums, k):
    ans = nums[k]
    minNum = nums[k]
    i = k
    j = k
    
    while i > -1 or j < len(nums):
        # Expand left while elements are >= minNum
        while i > -1 and nums[i] >= minNum:
            i -= 1
        
        # Expand right while elements are >= minNum
        while j < len(nums) and nums[j] >= minNum:
            j += 1
        
        # Calculate score for current subarray
        ans = max(ans, (j - i - 1) * minNum)
        
        # Update minNum to the larger of boundary elements
        left_val = nums[i] if i > -1 else -1
        right_val = nums[j] if j < len(nums) else -1
        minNum = max(left_val, right_val)
    
    return ans

# Test the function
nums = [2, 5, 4, 8, 5, 6]
k = 3
result = solve(nums, k)
print(f"Maximum score of good subarray: {result}")

The output of the above code is ?

Maximum score of good subarray: 20

How It Works

The algorithm starts at index k and expands the subarray in both directions. At each step, it finds the maximum contiguous subarray where all elements are greater than or equal to the current minimum. The score is calculated as minimum × length, and we track the maximum score encountered.

For the example [2,5,4,8,5,6] with k=3:

  • Start with subarray [8] at index 3, score = 8×1 = 8

  • Expand to [4,8,5,6], minimum = 4, score = 4×4 = 16

  • Expand to [5,4,8,5,6], minimum = 4, score = 4×5 = 20

Conclusion

This two-pointer expansion approach efficiently finds the maximum score by exploring all possible good subarrays. The algorithm runs in O(n) time complexity by expanding from the required index k.

Updated on: 2026-03-26T14:47:26+05:30

550 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements