# Program to find maximum score of a good subarray in Python

PythonServer Side ProgrammingProgramming

Suppose we have an array called nums and a value k. Consider the score of a subarray (i, j) is defined as minimum of subarray nums[i..j] * (j-i+1). Now, a good subarray is a subarray where i <= k <= j. We have to find the maximum possible score of a good subarray.

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

To solve this, we will follow these steps −

• ans := nums[k], minNum := nums[k]

• i := k, j := k

• while i > -1 or j < size of nums, do

• while i > -1 and nums[i] >= minNum, do

• i := i - 1

• while j < size of nums and nums[j] >= minNum, do

• j := j + 1

• ans := maximum of ans and ((j - i - 1) * minNum)

• minNum := maximum of (nums[i] if i > -1 otherwise -1) and (nums[j] if j < size of nums otherwise -1)

• return ans

## Example

Let us see the following implementation to get better understanding

def solve(nums, k):
ans = nums[k]
minNum = nums[k]
i = k
j = k
while i > -1 or j < len(nums):
while i > -1 and nums[i] >= minNum:
i -= 1
while j < len(nums) and nums[j] >= minNum:
j += 1
ans = max(ans, (j - i - 1) * minNum)
minNum = max(nums[i] if i > -1 else -1 , nums[j] if j <
len(nums) else -1)
return ans

nums = [2,5,4,8,5,6]
k = 3
print(solve(nums, k))

## Input

[2,5,4,8,5,6], 3


## Output

20
Updated on 08-Oct-2021 07:43:00