AlgoLounge

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.

Examples

Example 1

Input:  nums = [5,3,4,4,7,3,6,11,8,5,11]
Output: 3

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

nums is already a non-decreasing array. Therefore, we return 0.

Constraints

  • 1 <= nums.length <= 10⁵
  • 1 <= nums[i] <= 10⁹
TypeScript
Loading editor…
List of test cases (12)
Case 1
nums = [5,3,4,4,7,3,6,11,8,5,11]
Case 2
nums = [4,5,7,7,13]
Case 3
nums = [1]
Case 4
nums = [10,1,2,3,4,5]
Case 5
nums = [5,4,3,2,1]
Case 6
nums = [1,2,3,4,5]
Case 7
nums = [7,14,4,14,13,2,6,13]
Case 8
nums = [10,9,8,7,6,5,4,3,2,1]
Case 9
nums = [1,1,1,1]
Case 10
nums = [100,50,60,40,80,20,70]
Case 11
nums = [3,3,3,2,2,2,1,1,1,4]
Case 12
nums = [2,1,3,1,4,1,5,1]