Skip to content

2374. Steps To Make Array Non Decreasing

Difficulty: Medium

LeetCode Problem View on GitHub


2374. Steps to Make Array Non-decreasing

Medium


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

Solution

class Solution {
    static class Pair {
        int ind, count, node;
        public Pair(int ind, int count, int node) {
            this.ind = ind;
            this.count = count;
            this.node = node;
        }
        @Override
        public String toString() {
            return "(" + ind + " " + count + " " + node + ")";
        }
    }
    public int totalSteps(int[] nums) {
        int n = nums.length;
        int maxi = 0;
        Stack<Pair> st = new Stack<>();
        for (int i = n - 1; i >= 0; i--) {
            int current = nums[i];
            int count = 0;
            while (st.size() > 0 && current > st.peek().node) {
                count = Math.max(count + 1, st.peek().count);
                st.pop();
            }
            st.add(new Pair(i, count, current));
            maxi = Math.max(maxi, count);
        }
        return maxi;
    }
}

Complexity Analysis

  • Time Complexity: O(?)
  • Space Complexity: O(?)

Approach

Detailed explanation of the approach will be added here