返回介绍

solution / 2200-2299 / 2289.Steps to Make Array Non-decreasing / README_EN

发布于 2024-06-17 01:03:07 字数 4034 浏览 0 评论 0 收藏 0

2289. Steps to Make Array Non-decreasing

中文文档

Description

You are given a 0-indexed integer array nums. In one step, remove all elements nums[i] where nums[i - 1] > nums[i] for all 0 < i < nums.length.

Return _the number of steps performed until _nums_ becomes a non-decreasing array_.

 

Example 1:

Input: nums = [5,3,4,4,7,3,6,11,8,5,11]
Output: 3
Explanation: The following are the steps performed:
- Step 1: [5,3,4,4,7,3,6,11,8,5,11] becomes [5,4,4,7,6,11,11]
- Step 2: [5,4,4,7,6,11,11] becomes [5,4,7,11,11]
- Step 3: [5,4,7,11,11] becomes [5,7,11,11]
[5,7,11,11] is a non-decreasing array. Therefore, we return 3.

Example 2:

Input: nums = [4,5,7,7,13]
Output: 0
Explanation: nums is already a non-decreasing array. Therefore, we return 0.

 

Constraints:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 109

Solutions

Solution 1

class Solution:
  def totalSteps(self, nums: List[int]) -> int:
    stk = []
    ans, n = 0, len(nums)
    dp = [0] * n
    for i in range(n - 1, -1, -1):
      while stk and nums[i] > nums[stk[-1]]:
        dp[i] = max(dp[i] + 1, dp[stk.pop()])
      stk.append(i)
    return max(dp)
class Solution {
  public int totalSteps(int[] nums) {
    Deque<Integer> stk = new ArrayDeque<>();
    int ans = 0;
    int n = nums.length;
    int[] dp = new int[n];
    for (int i = n - 1; i >= 0; --i) {
      while (!stk.isEmpty() && nums[i] > nums[stk.peek()]) {
        dp[i] = Math.max(dp[i] + 1, dp[stk.pop()]);
        ans = Math.max(ans, dp[i]);
      }
      stk.push(i);
    }
    return ans;
  }
}
class Solution {
public:
  int totalSteps(vector<int>& nums) {
    stack<int> stk;
    int ans = 0, n = nums.size();
    vector<int> dp(n);
    for (int i = n - 1; i >= 0; --i) {
      while (!stk.empty() && nums[i] > nums[stk.top()]) {
        dp[i] = max(dp[i] + 1, dp[stk.top()]);
        ans = max(ans, dp[i]);
        stk.pop();
      }
      stk.push(i);
    }
    return ans;
  }
};
func totalSteps(nums []int) int {
  stk := []int{}
  ans, n := 0, len(nums)
  dp := make([]int, n)
  for i := n - 1; i >= 0; i-- {
    for len(stk) > 0 && nums[i] > nums[stk[len(stk)-1]] {
      dp[i] = max(dp[i]+1, dp[stk[len(stk)-1]])
      stk = stk[:len(stk)-1]
      ans = max(ans, dp[i])
    }
    stk = append(stk, i)
  }
  return ans
}
function totalSteps(nums: number[]): number {
  let ans = 0;
  let stack = [];
  for (let num of nums) {
    let max = 0;
    while (stack.length && stack[0][0] <= num) {
      max = Math.max(stack[0][1], max);
      stack.shift();
    }
    if (stack.length) max++;
    ans = Math.max(max, ans);
    stack.unshift([num, max]);
  }
  return ans;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文