#2945

Find Maximum Non-decreasing Array Length

Hard
ArrayBinary SearchDynamic ProgrammingStackQueueMonotonic StackMonotonic QueueDynamic ProgrammingArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses dynamic programming to keep track of the maximum length of a non-decreasing array as we process each element. This allows us to efficiently determine the maximum length without checking every subarray.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a dp array where dp[i] represents the maximum length of a non-decreasing array ending at index i.
  2. 2Step 2: Iterate through the nums array and update dp[i] based on the previous values.
  3. 3Step 3: If nums[i] can extend the non-decreasing sequence from nums[i-1], update dp[i].
  4. 4Step 4: Return the maximum value in the dp array.
solution.py7 lines
1def maxNonDecreasingLength(nums):
2    n = len(nums)
3    dp = [1] * n
4    for i in range(1, n):
5        if nums[i] >= nums[i - 1]:
6            dp[i] = dp[i - 1] + 1
7    return max(dp)

Complexity note: This complexity is efficient because we only make a single pass through the array, updating our dp array.

  • 1Dynamic programming can significantly reduce the time complexity of problems involving sequences.
  • 2Understanding how to build up solutions incrementally is key to mastering DSA.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.