Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #2263: Make Array Non-decreasing or Non-increasing

In this guide, we solve Leetcode #2263 Make Array Non-decreasing or Non-increasing in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

You are given a 0-indexed integer array nums. In one operation, you can: Choose an index i in the range 0 <= i < nums.length Set nums[i] to nums[i] + 1 or nums[i] - 1 Return the minimum number of operations to make nums non-decreasing or non-increasing.

Quick Facts

  • Difficulty: Hard
  • Premium: Yes
  • Tags: Greedy, Dynamic Programming

Intuition

The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.

A carefully chosen DP state captures exactly what we need to build the final answer.

Approach

Define the DP state and recurrence, then compute states in the correct order.

Optionally compress space once the recurrence is clear.

Steps:

  • Choose a DP state definition.
  • Write the recurrence and base cases.
  • Compute states in the correct order.

Example

Input: nums = [3,2,4,5,0] Output: 4 Explanation: One possible way to turn nums into non-increasing order is to: - Add 1 to nums[1] once so that it becomes 3. - Subtract 1 from nums[2] once so it becomes 3. - Subtract 1 from nums[3] twice so it becomes 3. After doing the 4 operations, nums becomes [3,3,3,3,0] which is in non-increasing order. Note that it is also possible to turn nums into [4,4,4,4,0] in 4 operations. It can be proven that 4 is the minimum number of operations needed.

Python Solution

class Solution: def convertArray(self, nums: List[int]) -> int: def solve(nums): n = len(nums) f = [[0] * 1001 for _ in range(n + 1)] for i, x in enumerate(nums, 1): mi = inf for j in range(1001): if mi > f[i - 1][j]: mi = f[i - 1][j] f[i][j] = mi + abs(x - j) return min(f[n]) return min(solve(nums), solve(nums[::-1]))

Complexity

The time complexity is O(n·m) (typical). The space complexity is O(n·m) or optimized.

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy