hardStackPattern: Monotonic Stack

Minimum Replacements for Non-Decreasing Order Solution

Problem Statement

Given an array of integers, find the minimum number of replacements required to achieve a non-decreasing order.

Examples

Example 1:
Input:[5, 3, 7, 2, 1, 9]
Output:2
Explanation: Replace 9 with 7, and then the array will be in non-decreasing order.

Constraints

  • The input array will not be empty.
  • The input array will contain unique integers.
  • The input array will not contain negative numbers.
Time: O(n) Space: O(n)
Use a monotonic stack to efficiently find the minimum number of replacements, with a time complexity of O(n) and a space complexity of O(n).

Run, Test & Submit Code

Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.

Solve on Interactive Workspace

Tested Solutions

// write your code here