---
description: Greedy
---

# LeetCode 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._

**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.
```

**Constraints:**

* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 2 * 104`
* `0 <= k < nums.length`

## Solution

[English Version in Youtube](https://youtu.be/An3r5pFOKLc)

[中文版解答Youtube Link](https://youtu.be/Xiznf9co2sM)

[中文版解答Bilibili Link](https://www.bilibili.com/video/BV14V411Y7kr/)

```
class Solution {
public:
    int maximumScore(vector<int>& nums, int k) {
        int mini = nums[k];
        int ans = mini;
        
        int i = k;
        int j = k;
        
        while (i > 0 || j < nums.size() - 1) {
            if (i == 0 || (j+1 < nums.size() && nums[i-1] <= nums[j+1])) {
                j++;
                mini = min(mini, nums[j]);
                ans = max(ans, mini * (j - i + 1));
            } else {
                i--;
                mini = min(mini, nums[i]);
                ans = max(ans, mini * (j - i + 1));
            }
        }
        
        return ans;
    }
};
```
