|
| 1 | +# 2289. Steps to Make Array Non-decreasing |
| 2 | + |
| 3 | +- Difficulty: Medium. |
| 4 | +- Related Topics: Array, Linked List, Stack, Monotonic Stack. |
| 5 | +- Similar Questions: Remove One Element to Make the Array Strictly Increasing. |
| 6 | + |
| 7 | +## Problem |
| 8 | + |
| 9 | +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`. |
| 10 | + |
| 11 | +Return **the number of steps performed until **`nums`** becomes a **non-decreasing** array**. |
| 12 | + |
| 13 | + |
| 14 | +Example 1: |
| 15 | + |
| 16 | +``` |
| 17 | +Input: nums = [5,3,4,4,7,3,6,11,8,5,11] |
| 18 | +Output: 3 |
| 19 | +Explanation: The following are the steps performed: |
| 20 | +- Step 1: [5,3,4,4,7,3,6,11,8,5,11] becomes [5,4,4,7,6,11,11] |
| 21 | +- Step 2: [5,4,4,7,6,11,11] becomes [5,4,7,11,11] |
| 22 | +- Step 3: [5,4,7,11,11] becomes [5,7,11,11] |
| 23 | +[5,7,11,11] is a non-decreasing array. Therefore, we return 3. |
| 24 | +``` |
| 25 | + |
| 26 | +Example 2: |
| 27 | + |
| 28 | +``` |
| 29 | +Input: nums = [4,5,7,7,13] |
| 30 | +Output: 0 |
| 31 | +Explanation: nums is already a non-decreasing array. Therefore, we return 0. |
| 32 | +``` |
| 33 | + |
| 34 | + |
| 35 | +**Constraints:** |
| 36 | + |
| 37 | + |
| 38 | + |
| 39 | +- `1 <= nums.length <= 105` |
| 40 | + |
| 41 | +- `1 <= nums[i] <= 109` |
| 42 | + |
| 43 | + |
| 44 | + |
| 45 | +## Solution |
| 46 | + |
| 47 | +```javascript |
| 48 | +/** |
| 49 | + * @param {number[]} nums |
| 50 | + * @return {number} |
| 51 | + */ |
| 52 | +var totalSteps = function(nums) { |
| 53 | + var dp = Array(nums.length).fill(0); |
| 54 | + var stack = []; |
| 55 | + for (var i = nums.length - 1; i >= 0; i--) { |
| 56 | + while (stack.length && nums[i] > nums[stack[stack.length - 1]]) { |
| 57 | + dp[i] = Math.max(dp[i] + 1, dp[stack.pop()]); |
| 58 | + } |
| 59 | + stack.push(i); |
| 60 | + } |
| 61 | + return Math.max(...dp); |
| 62 | +}; |
| 63 | +``` |
| 64 | + |
| 65 | +**Explain:** |
| 66 | + |
| 67 | +nope. |
| 68 | + |
| 69 | +**Complexity:** |
| 70 | + |
| 71 | +* Time complexity : O(n). |
| 72 | +* Space complexity : O(n). |
1 commit comments
vercel[bot] commentedon Sep 8, 2023
Successfully deployed to the following URLs:
leetcode-javascript – ./
leetcode-javascript-git-master-baffinlee.vercel.app
leetcode-javascript-baffinlee.vercel.app
leetcode-javascript.vercel.app