mirror of https://github.com/doocs/leetcode.git
|
…
|
||
|---|---|---|
| .. | ||
| README.md | ||
| README_EN.md | ||
| Solution.cpp | ||
| Solution.go | ||
| Solution.java | ||
| Solution.py | ||
| Solution.ts | ||
README_EN.md
| comments | difficulty | edit_url | rating | source | tags | ||||
|---|---|---|---|---|---|---|---|---|---|
| true | Medium | https://github.com/doocs/leetcode/edit/main/solution/3500-3599/3523.Make%20Array%20Non-decreasing/README_EN.md | 1435 | Weekly Contest 446 Q2 |
|
3523. Make Array Non-decreasing
Description
You are given an integer array nums. In one operation, you can select a subarray and replace it with a single element equal to its maximum value.
Return the maximum possible size of the array after performing zero or more operations such that the resulting array is non-decreasing.
Example 1:
Input: nums = [4,2,5,3,5]
Output: 3
Explanation:
One way to achieve the maximum size is:
- Replace subarray
nums[1..2] = [2, 5]with5→[4, 5, 3, 5]. - Replace subarray
nums[2..3] = [3, 5]with5→[4, 5, 5].
The final array [4, 5, 5] is non-decreasing with size 3.
Example 2:
Input: nums = [1,2,3]
Output: 3
Explanation:
No operation is needed as the array [1,2,3] is already non-decreasing.
Constraints:
1 <= nums.length <= 2 * 1051 <= nums[i] <= 2 * 105
Solutions
Solution 1
Python3
class Solution:
def maximumPossibleSize(self, nums: List[int]) -> int:
ans = mx = 0
for x in nums:
if mx <= x:
ans += 1
mx = x
return ans
Java
class Solution {
public int maximumPossibleSize(int[] nums) {
int ans = 0, mx = 0;
for (int x : nums) {
if (mx <= x) {
++ans;
mx = x;
}
}
return ans;
}
}
C++
class Solution {
public:
int maximumPossibleSize(vector<int>& nums) {
int ans = 0, mx = 0;
for (int x : nums) {
if (mx <= x) {
++ans;
mx = x;
}
}
return ans;
}
};
Go
func maximumPossibleSize(nums []int) int {
ans, mx := 0, 0
for _, x := range nums {
if mx <= x {
ans++
mx = x
}
}
return ans
}
TypeScript
function maximumPossibleSize(nums: number[]): number {
let [ans, mx] = [0, 0];
for (const x of nums) {
if (mx <= x) {
++ans;
mx = x;
}
}
return ans;
}