Leetcode Problem:
Summary
- Given an integer array and an integer k, return the length of the shortest non-empty subarray with a sum of at least k.
Approach
- Use a deque to store the prefix sum and its corresponding end index
- Iterate through the array, updating the prefix sum and checking if it's greater than or equal to k
- If it is, update the result with the minimum length
- If the prefix sum minus the front element is greater than or equal to k, remove the front element from the deque
- If the back element's prefix sum is greater than the current prefix sum, remove it from the deque
- Finally, return the result or -1 if no such subarray exists.
Complexity
- O(n) where n is the length of the array
Explanation
- The time complexity is O(n) because we're doing a single pass through the array
- The space complexity is O(n) for storing the deque.
Solution Code:
class Solution {
public:
int shortestSubarray(vector& nums, int k) {
int res = INT_MAX;
long long curSum = 0;
deque> q; // (prefix_sum, end_idx)
for(int r = 0; r < nums.size(); r++){
curSum += nums[r];
if(curSum >= k){
res = min(res, r + 1);
}
while (!q.empty() && curSum - q.front().first >= k){
auto [prefix, endIdx] = q.front();
q.pop_front();
res = min(res, r - endIdx);
}
while (!q.empty() && q.back().first > curSum) {
q.pop_back();
}
q.push_back({curSum, r});
}
return res == INT_MAX ? -1 : res;
}
};
'알고리즘' 카테고리의 다른 글
Maximum Sum of Distinct Subarrays With Length K (0) | 2025.02.22 |
---|---|
Defuse the Bomb (0) | 2025.02.22 |
Find the Power of K-Size Subarrays I (0) | 2025.02.22 |
Find Elements in a Contaminated Binary Tree (0) | 2025.02.21 |
Shortest Subarray to be Removed to Make Array Sorted (0) | 2025.02.21 |