To maximize the size of the resulting non-decreasing array, we want to merge as few elements as possible. We can use a monotonic stack to greedily merge elements when a decrease is found, always merging the rightmost possible subarray to its maximum.
If the stack is empty or the current number is greater than or equal to the top, push it onto the stack.
If the current number is less than the top, pop elements from the stack until the stack is empty or the top is less than or equal to the current number, then push the maximum of the popped elements and the current number.
classSolution {
public:int maxArrayLength(vector<int>& nums) {
vector<int> stk;
for (int x : nums) {
while (!stk.empty() && x < stk.back()) {
x = max(x, stk.back());
stk.pop_back();
}
stk.push_back(x);
}
return stk.size();
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
funcmaxArrayLength(nums []int) int {
stk:= []int{}
for_, x:=rangenums {
for len(stk) > 0&&x < stk[len(stk)-1] {
ifx < stk[len(stk)-1] {
x = max(x, stk[len(stk)-1])
}
stk = stk[:len(stk)-1]
}
stk = append(stk, x)
}
return len(stk)
}
func max(a, bint) int { ifa > b { returna } else { returnb } }
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
publicintmaxArrayLength(int[] nums) {
Deque<Integer> stk =new ArrayDeque<>();
for (int x : nums) {
while (!stk.isEmpty() && x < stk.peekLast()) {
x = Math.max(x, stk.pollLast());
}
stk.addLast(x);
}
return stk.size();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
funmaxArrayLength(nums: IntArray): Int {
val stk = ArrayDeque<Int>()
for (x0 in nums) {
var x = x0
while (stk.isNotEmpty() && x < stk.last()) {
x = maxOf(x, stk.removeLast())
}
stk.addLast(x)
}
return stk.size
}
}
1
2
3
4
5
6
7
8
classSolution:
defmaxArrayLength(self, nums: list[int]) -> int:
stk = []
for x in nums:
while stk and x < stk[-1]:
x = max(x, stk.pop())
stk.append(x)
return len(stk)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
impl Solution {
pubfnmax_array_length(nums: Vec<i32>) -> i32 {
letmut stk = Vec::new();
formut x in nums {
whilelet Some(&top) = stk.last() {
if x < top {
x = x.max(stk.pop().unwrap());
} else {
break;
}
}
stk.push(x);
}
stk.len() asi32 }
}