Loading...

10-22 leetcode-1793

链接 1793. Maximum Score of a Good Subarray

题目

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.

题解

这题我用的是类似贪心的做法,双指针向外扩展

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution:
def maximumScore(self, nums: list[int], k: int) -> int:
left, right = k, k
min_num = nums[k]
result = min_num
while left > 0 or right < len(nums) - 1:
if left == 0 or right < len(nums) - 1 and nums[left - 1] < nums[right + 1]:
right += 1
else:
left -= 1
min_num = min(min_num, nums[left], nums[right])
result = max(result, min_num * (right - left + 1))
return result

Comment