Leetcode 2970. Count the Number of Incremovable Subarrays I
You are given an array of integers nums
. A subarray [nums[i], nums[i + 1], ..., nums[j]]
is considered as incremovable if the following two conditions are met:
Your task is to return the number of different incremovable subarrays.
Input: nums = [1, 2, 3, 4]
Output: 4
Explanation: There are 4 incremovable subarrays:
- [1, 2, 3, 4] -> Sum = 10 (even) and sum of remaining array (after removing this subarray) can never be >= 10
- [2, 3, 4] -> Sum = 9 (odd)
- [1, 2, 3] -> Sum = 6 (even) and sum of remaining array (after removing this subarray) cannot be >= 10
- [3, 4] -> Sum = 7 (odd)
Two more subarrays can also be counted: [2], [4].
n
) and the values inside the array?
1 <= n <= 10^4
and -10^5 <= nums[i] <= 10^5
.To solve this problem, we can break it down into the following steps:
S
of the array.[nums[i], nums[i + 1], ..., nums[j]]
and their sums.S
.Here is the C++ implementation:
#include <vector>
#include <numeric> // For std::accumulate
class Solution {
public:
int countIncremovableSubarrays(std::vector<int>& nums) {
// Calculate the total sum of the array
int total_sum = std::accumulate(nums.begin(), nums.end(), 0);
int count = 0;
int n = nums.size();
// Iterate over all possible subarrays
for (int i = 0; i < n; ++i) {
int current_sum = 0;
for (int j = i; j < n; ++j) {
current_sum += nums[j];
// Check if the sum of the subarray is even
if (current_sum % 2 == 0) {
// Calculate the remaining sum of the array if this subarray is removed
int remaining_sum = total_sum - current_sum;
// Check if the remaining sum is less than the original total sum
if (remaining_sum < total_sum) {
++count;
}
}
}
}
return count;
}
};
The time complexity of this solution is (O(n^2)), where (n) is the length of the array. This is because we are iterating over all possible subarrays, leading to a nested loop.
In total, the nested loops will run (n \times n = n^2) times in the worst case, making the overall time complexity (O(n^2)).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?