LeetCode 2289. Steps to Make Array Non-decreasing

原题链接在这里:https://leetcode.com/problems/steps-to-make-array-non-decreasing/

题目:

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

题解:

For a num[j], if there is num[i] with i < j and num[i] > num[j]. Then num[j] will be removed.

If not, then num[j] will remain in the final non-decreasing array.

When it needs to be removed, the question becomes how many steps it needs to be remvoed.

This is equal as the distance with previous larger num[i].

We need monotonic decreasing stack. stack of pair. pair[num and its step].

While the stack is not empty and peek value <= current num, pop get cur pair.

Update count = Math.max(count, cur[1] + 1). As it needs one more step to remove current num.

If the stack becomes empty, that means there is no previous non-smaller num[i]. It doesn't not need to be removed. Then count = 0.

Either way, update the result and push pair, num and count into stack.

Time Complexity: O(n). n = nums.length.

Note: count is initialized as 1. As when there is one bigger element on its left, initialize count as 1.

Space: o(n).

AC Java:

 1 class Solution {
 2     public int totalSteps(int[] nums) {
 3         if(nums == null || nums.length == 0){
 4             return 0;
 5         }
 6 
 7         Stack<int []> stk = new Stack<>();
 8         int res = 0;
 9         for(int num : nums){
10             int count = 1;
11             while(!stk.isEmpty() && num >= stk.peek()[0]){
12                 int [] top = stk.pop();
13                 count = Math.max(count, top[1] + 1);
14             }
15 
16             if(stk.isEmpty()){
17                 count = 0;
18             }
19 
20             res = Math.max(res, count);
21             stk.push(new int[]{num, count});
22         }
23 
24         return res;
25     }
26 }

 

posted @ 2022-06-24 13:45  Dylan_Java_NYC  阅读(287)  评论(0编辑  收藏  举报