HardNo. 2945
Find Maximum Non-decreasing Array Length — LeetCode 2945 Python Solution
- Pattern
- Stack
- Topics
- Stack, Queue, Array, Binary Search, Dynamic Programming, Monotonic Queue, Monotonic Stack
- Reading time
- 2 min
- Source
- leetcode.com
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
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
- Time
- O(log n) or O(n log n)
- Space · auxiliary
- O(1)
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
| No. | Problem | Difficulty |
|---|---|---|
| 2940 | Find Building Where Alice and Bob Can Meet | Hard |
| 0456 | 132 Pattern | Medium |
| 2454 | Next Greater Element IV | Hard |
| 2736 | Maximum Sum Queries | Hard |
| 0084 | Largest Rectangle in Histogram | Hard |
| 0300 | Longest Increasing Subsequence | Medium |
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.