Find Maximum Non-decreasing Array Length - 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.

For example, if the given array is [1,3,5,6] and you select subarray [3,5], the array will convert to [1,8,6].

Return the maximum length of a non-decreasing array that can be made after applying operations.

A subarray is a contiguous non-empty sequence of elements within an array.

Input & Output

Example 1 — Basic Merging
$ Input: nums = [5,2,4,6,3,7]
Output: 3
💡 Note: We can merge subarrays: [5] + [2,4] + [6,3,7] = [5,6,16]. This gives us a non-decreasing array of length 3.
Example 2 — Already Non-decreasing
$ Input: nums = [1,3,5,6]
Output: 4
💡 Note: Array is already non-decreasing, so no merging needed. Keep all elements: [1,3,5,6]. Length is 4.
Example 3 — Single Element
$ Input: nums = [1]
Output: 1
💡 Note: Single element is always non-decreasing. No operations needed. Length is 1.

Constraints

  • 1 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Find Maximum Non-decreasing Array Length INPUT nums array (6 elements) 5 [0] 2 [1] 4 [2] 6 [3] 3 [4] 7 [5] Goal: Merge subarrays to create longest non-decreasing array by replacing with sums Input: [5,2,4,6,3,7] Length = 6 ALGORITHM STEPS 1 Use DP with prefix sums dp[i] = max length ending at i 2 Track last segment sum Ensure non-decreasing order 3 Binary search optimization Find valid previous states 4 Merge adjacent elements Maximize result length Optimal Merging: [5,2,4,6,3,7] [5+2, 4+6, 3+7] merge [7, 10, 10] OK 7 <= 10 <= 10 valid! FINAL RESULT Merged Non-decreasing Array: 7 10 10 5+2 4+6 3+7 Output: 3 Verification: Original length: 6 Result length: 3 Non-decreasing: OK Maximum possible: OK Key Insight: The optimal solution uses dynamic programming with monotonic deque. For each position, we track the minimum last segment sum that achieves maximum length. Prefix sums enable O(1) range sum queries, and binary search on the deque gives O(n log n) complexity. Greedy merging from left ensures optimality. TutorialsPoint - Find Maximum Non-decreasing Array Length | Optimal Solution
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
8.5K Views
Medium Frequency
~25 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen