Find Maximum Non-decreasing Array Length — LeetCode 2945 Python Solution

HardStackQueueArrayBinary SearchDynamic ProgrammingMonotonic QueueMonotonic Stack
Problem
#2945
Pattern
Stack
Reading time
2 min

The problem

You are given a 0-indexed integer array nums. You can perform any number of operations, where each operation involves selecting a subarray of the array and replacing it with the sum of its elements.

Example

Input
nums = [5,2,2]
Output
1
Explanation
This array with length 3 is not non-decreasing.

Python solution

Python
class Solution:
    def findMaximumLength(self, nums: List[int]) -> int:
        n = len(nums)
        s = list(accumulate(nums, initial=0))
        f = [0] * (n + 1)
        pre = [0] * (n + 2)
        for i in range(1, n + 1):
            pre[i] = max(pre[i], pre[i - 1])
            f[i] = f[pre[i]] + 1
            j = bisect_left(s, s[i] * 2 - s[pre[i]])
            pre[j] = i
        return f[n]

Complexity

MeasureComplexity
TimeO(log n) or O(n log n)
SpaceO(1) auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 2945. Find Maximum Non-decreasing Array Length is filed here because LeetCode tags it Stack and Queue, which is the vocabulary this hub collects.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2945. Find Maximum Non-decreasing Array Length?
LeetCode 2945. Find Maximum Non-decreasing Array Length is rated Hard on LeetCode.
What topics does LeetCode 2945. Find Maximum Non-decreasing Array Length cover?
LeetCode 2945. Find Maximum Non-decreasing Array Length is tagged Stack, Queue, Array, Binary Search, Dynamic Programming, Monotonic Queue and Monotonic Stack on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview