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: nums =[5,2,2]Output: 1Explanation: This array with length 3is not non-decreasing.We have two ways to make the array length two.First, choosing subarray [2,2] converts the array to [5,4].Second, choosing subarray [5,2] converts the array to [7,2].In these two ways the array is not non-decreasing.And if we choose subarray [5,2,2] and replace it with[9] it becomes non-decreasing.So the answer is1.
Input: nums =[4,3,2,6]Output: 3Explanation: Replacing [3,2]with[5] converts the given array to [4,5,6] that is non-decreasing.Because the given array is not non-decreasing, the maximum possible answer is3.
We want to maximize the length of a non-decreasing array after repeatedly replacing any subarray with its sum. The key is that after each operation, the array shrinks, and the sum can be placed anywhere, so we can always merge adjacent non-decreasing segments. The problem reduces to finding the length of the longest non-decreasing subarray that can be formed by merging sums.
classSolution {
publicintmaxNonDecreasingLength(int[] nums) {
Deque<Long> stk =new ArrayDeque<>();
for (int x : nums) {
long sum = x;
while (!stk.isEmpty() && sum < stk.peekLast()) {
sum += stk.pollLast();
}
stk.addLast(sum);
}
return stk.size();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
funmaxNonDecreasingLength(nums: IntArray): Int {
val stk = ArrayDeque<Long>()
for (x in nums) {
var sum = x.toLong()
while (stk.isNotEmpty() && sum < stk.last()) {
sum += stk.removeLast()
}
stk.addLast(sum)
}
return stk.size
}
}
1
2
3
4
5
6
7
8
9
classSolution:
defmaxNonDecreasingLength(self, nums: list[int]) -> int:
stk: list[int] = []
for x in nums:
s = x
while stk and s < stk[-1]:
s += stk.pop()
stk.append(s)
return len(stk)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
impl Solution {
pubfnmax_non_decreasing_length(nums: Vec<i32>) -> i32 {
letmut stk: Vec<i64>=vec![];
for&x in&nums {
letmut sum = x asi64;
whilelet Some(&last) = stk.last() {
if sum < last {
sum += stk.pop().unwrap();
} else {
break;
}
}
stk.push(sum);
}
stk.len() asi32 }
}