You are given a 0-indexed array of positive integers nums.
A subarray of nums is called incremovable if nums becomes strictly increasing on removing the subarray. For example, the subarray [3, 4] is an incremovable subarray of [5, 3, 4, 6, 7] because removing this subarray changes the array [5, 3, 4, 6, 7] to [5, 6, 7] which is strictly increasing.
Return the total number ofincremovable subarrays ofnums.
Note that an empty array is considered strictly increasing.
A subarray is a contiguous non-empty sequence of elements within an array.
Input: nums =[1,2,3,4]Output: 10Explanation: The 10 incremovable subarrays are:[1],[2],[3],[4],[1,2],[2,3],[3,4],[1,2,3],[2,3,4], and [1,2,3,4], because on removing any one of these subarrays nums becomes strictly increasing. Note that you cannot select an empty subarray.
Input: nums =[6,5,7,8]Output: 7Explanation: The 7 incremovable subarrays are:[5],[6],[5,7],[6,5],[5,7,8],[6,5,7] and [6,5,7,8].It can be shown that there are only 7 incremovable subarrays in nums.
Input: nums =[8,7,6,6]Output: 3Explanation: The 3 incremovable subarrays are:[8,7,6],[7,6,6], and [8,7,6,6]. Note that [8,7]is not an incremovable subarray because after removing [8,7] nums becomes [6,6], which is sorted in ascending order but not strictly increasing.
A subarray is incremovable if, after removing it, the remaining array is strictly increasing. Since the array is small (n ≤ 50), we can check all possible subarrays by removing them and verifying if the result is strictly increasing.
classSolution {
public:int incremovableSubarrayCount(vector<int>& nums) {
int n = nums.size(), ans =0;
for (int l =0; l < n; ++l) {
for (int r = l; r < n; ++r) {
vector<int> arr;
for (int i =0; i < l; ++i) arr.push_back(nums[i]);
for (int i = r+1; i < n; ++i) arr.push_back(nums[i]);
bool ok = true;
for (int i =1; i < arr.size(); ++i) {
if (arr[i] <= arr[i-1]) ok = false;
}
if (ok) ans++;
}
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classSolution {
publicintincremovableSubarrayCount(int[] nums) {
int n = nums.length, ans = 0;
for (int l = 0; l < n; ++l) {
for (int r = l; r < n; ++r) {
List<Integer> arr =new ArrayList<>();
for (int i = 0; i < l; ++i) arr.add(nums[i]);
for (int i = r+1; i < n; ++i) arr.add(nums[i]);
boolean ok =true;
for (int i = 1; i < arr.size(); ++i) {
if (arr.get(i) <= arr.get(i-1)) ok =false;
}
if (ok) ans++;
}
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
classSolution:
defincremovableSubarrayCount(self, nums: list[int]) -> int:
n = len(nums)
ans =0for l in range(n):
for r in range(l, n):
arr = nums[:l] + nums[r+1:]
if all(arr[i] > arr[i-1] for i in range(1, len(arr))):
ans +=1return ans