

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to find maximum score of a good subarray in Python
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
- Related Questions & Answers
- Program to find maximum product of contiguous subarray in Python
- Program to find maximum score of brick removal game in Python
- Program to find maximum score in stone game in Python
- Program to find maximum subarray min-product in Python
- Program to find maximum score from removing stones in Python
- Program to find maximum absolute sum of any subarray in Python
- Program to find maximum ascending subarray sum using Python
- Program to find maximum additive score by deleting numbers in Python
- Program to find maximum score from performing multiplication operations in Python
- Program to find maximum length of subarray with positive product in Python
- C++ Program to find maximum score of bit removal game
- Program to find out the sum of the maximum subarray after a operation in Python
- Program to find maximum score we can get in jump game in Python
- C++ program to find perfect array of size n whose subarray is a good array
- Program to find the maximum score from all possible valid paths in Python