1793. Maximum Score of a Good Subarray (Leetcode)
You are given an array of integers nums (0-indexed) and an integer k.
The score of a subarray (i, j) is defined as min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1). A good subarray is a subarray where i <= k <= j.
Return the maximum possible score of a good subarray.
Example: 1
Input: nums = [1,4,3,7,4,5], k = 3
Output: 15
Explanation: The optimal subarray is (1, 5) with a score of min(4,3,7,4,5) * (5-1+1) = 3 * 5 = 15.
Example: 2
Input: nums = [5,5,4,5,4,1,1,1], k = 0
Output: 20
Explanation: The optimal subarray is (0, 4) with a score of min(5,5,4,5,4) * (4-0+1) = 4 * 5 = 20.
- 1 <= nums.length <= 10 ^ 5
 - 1 <= nums[i] <= 2 * 10 ^ 4
 - 0 <= k < nums.length
 
- In this problem we have to choose a sub-array [i, j] where i <= k and j >= k. So we can clearly observe that, the smallest interval we can take is [k, k].
 - So we start out by considering [k, k] to be the first interval (i.e i = k and j = k) and max as nums[k].
 - Also we will have a variable min to store min value from i to j.
 
- Then we will check to the left of range(i.e i - 1) and right of range(i.e j + 1).
 - Then if nums[i - 1] > nums[j + 1], we will decrement i to i - 1, otherwise increment j to j + 1.
 By continuing in this way we will sequentially process all ranges greedily, which can potentially contribute to our solution. - Also remember to handle edge cases where i == 0 and j == nums.length - 1 accordingly.
 
Comments
Post a Comment
If you have any queries or need solution for any problem, please let me know.