Input: nums =[7,6,5,4,3,2,1,6,10,11]Output: 8Explanation: Take the subarray [7,6,5,4,3,2,1,6].The first element is7 and the last one is6 so the condition is met.Hence, the answer would be the length of the subarray or 8.It can be shown that there aren't any subarrays with the given condition with a length greater than 8.
Example 2:
1
2
3
4
5
6
Input: nums =[57,55,50,60,61,58,63,59,64,60,63]Output: 6Explanation: Take the subarray [61,58,63,59,64,60].The first element is61 and the last one is60 so the condition is met.Hence, the answer would be the length of the subarray or 6.It can be shown that there aren't any subarrays with the given condition with a length greater than 6.
Example 3:
1
2
3
Input: nums =[1,2,3,4]Output: 0Explanation: Since there are no semi-decreasing subarrays in the given array, the answer is0.
A subarray is semi-decreasing if its first element is strictly greater than its last. For each possible starting index, we can extend the subarray to the right as long as the first element is greater than the current last element, and track the maximum length found.
classSolution {
public:int maxSemiDecreasingLength(vector<int>& nums) {
int n = nums.size(), ans =0;
for (int l =0; l < n-1; ++l) {
for (int r = l+1; r < n; ++r) {
if (nums[l] > nums[r]) ans = max(ans, r-l+1);
}
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
funcmaxSemiDecreasingLength(nums []int) int {
n, ans:= len(nums), 0forl:=0; l < n-1; l++ {
forr:=l+1; r < n; r++ {
ifnums[l] > nums[r] &&r-l+1 > ans {
ans = r-l+1 }
}
}
returnans}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
publicintmaxSemiDecreasingLength(int[] nums) {
int n = nums.length, ans = 0;
for (int l = 0; l < n-1; ++l) {
for (int r = l+1; r < n; ++r) {
if (nums[l]> nums[r]) ans = Math.max(ans, r-l+1);
}
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
funmaxSemiDecreasingLength(nums: IntArray): Int {
val n = nums.size
var ans = 0for (l in0 until n-1) {
for (r in l+1 until n) {
if (nums[l] > nums[r]) ans = maxOf(ans, r-l+1)
}
}
return ans
}
}
1
2
3
4
5
6
7
8
9
classSolution:
defmaxSemiDecreasingLength(self, nums: list[int]) -> int:
n = len(nums)
ans =0for l in range(n-1):
for r in range(l+1, n):
if nums[l] > nums[r]:
ans = max(ans, r-l+1)
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
impl Solution {
pubfnmax_semi_decreasing_length(nums: Vec<i32>) -> i32 {
let n = nums.len();
letmut ans =0;
for l in0..n-1 {
for r in l+1..n {
if nums[l] > nums[r] {
ans = ans.max((r-l+1) asi32);
}
}
}
ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
maxSemiDecreasingLength(nums: number[]):number {
constn=nums.length;
letans=0;
for (letl=0; l<n-1; ++l) {
for (letr=l+1; r<n; ++r) {
if (nums[l] >nums[r]) ans= Math.max(ans, r-l+1);
}
}
returnans;
}
}