Problem: 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.


Python solution:
import math
import itertools
import bisect
import collections
import string
import heapq
import functools
import sortedcontainers
from typing import List, Dict, Tuple, Iterator

class Solution:
  def maximumScore(self, nums: List[int], k: int) -> int:
    ans = 0
    stack = []

    for i in range(len(nums) + 1):
      while stack and (i == len(nums) or nums[stack[-1]] > nums[i]):
        h = nums[stack.pop()]
        w = i - stack[-1] - 1 if stack else i
        if (not stack or stack[-1] + 1 <= k) and i - 1 >= k:
          ans = max(ans, h * w)
      stack.append(i)

    return ans


Java solution:
class Solution {
  // Similar to 84. Largest Rectangle in Histogram
  public int maximumScore(int[] nums, int k) {
    int ans = 0;
    Deque<Integer> stack = new ArrayDeque<>();

    for (int i = 0; i <= nums.length; ++i) {
      while (!stack.isEmpty() && (i == nums.length || nums[stack.peek()] > nums[i])) {
        final int h = nums[stack.pop()];
        final int w = stack.isEmpty() ? i : i - stack.peek() - 1;
        if ((stack.isEmpty() || stack.peek() + 1 <= k) && i - 1 >= k)
          ans = Math.max(ans, h * w);
      }
      stack.push(i);
    }

    return ans;
  }
}


C++ solution:
class Solution {
 public:
  // Similar to 84. Largest Rectangle in Histogram
  int maximumScore(vector<int>& nums, int k) {
    int ans = 0;
    stack<int> stack;

    for (int i = 0; i <= nums.size(); ++i) {
      while (!stack.empty() &&
             (i == nums.size() || nums[stack.top()] > nums[i])) {
        const int h = nums[stack.top()];
        stack.pop();
        const int w = stack.empty() ? i : i - stack.top() - 1;
        if ((stack.empty() || stack.top() + 1 <= k) && i - 1 >= k)
          ans = max(ans, h * w);
      }
      stack.push(i);
    }

    return ans;
  }
};