Premium Only Content

862. Shortest Subarray with Sum at Least K
Given an integer array nums and an integer k, return the length of the shortest non-empty subarray of nums with a sum of at least k. If there is no such subarray, return -1.
A subarray is a contiguous part of an array.
Example 1:
Input: nums = [1], k = 1
Output: 1
Example 2:
Input: nums = [1,2], k = 4
Output: -1
Example 3:
Input: nums = [2,-1,2], k = 3
Output: 3
Constraints:
1 <= nums.length <= 105
-105 <= nums[i] <= 105
1 <= k <= 109
class Solution {
public:
int shortestSubarray(vector<int>& nums, int k) {
int n = nums.size();
// Initialize result to the maximum possible integer value
int shortestSubarrayLength = INT_MAX;
long long cumulativeSum = 0;
// Min-heap to store cumulative sum and its corresponding index
priority_queue<pair<long long, int>, vector<pair<long long, int>>,greater<>> prefixSumHeap;
// Iterate through the array
for (int i = 0; i < n; i++) {
// Update cumulative sum
cumulativeSum += nums[i];
// If cumulative sum is already >= k, update shortest length
if (cumulativeSum >= k) {
shortestSubarrayLength = min(shortestSubarrayLength, i + 1);
}
// Remove subarrays from heap that can form a valid subarray
while (!prefixSumHeap.empty() && cumulativeSum - prefixSumHeap.top().first >= k) {
// Update shortest subarray length
shortestSubarrayLength = min(shortestSubarrayLength, i - prefixSumHeap.top().second);
prefixSumHeap.pop();
}
// Add current cumulative sum and index to heap
prefixSumHeap.emplace(cumulativeSum, i);
}
// Return -1 if no valid subarray found
return shortestSubarrayLength == INT_MAX ? -1 : shortestSubarrayLength;
}
};
-
LIVE
vivafrei
2 hours agoWall Street Journal DOUBLING DOWN on Epstein! Lawyer in Canada DEBANKED! AND MORE!
11,310 watching -
4:42:20
Donut Operator
4 hours agoI'M BACK/ CRIME/ GAMEBOY CAMERA CHAD
75.6K4 -
9:51
Warren Smith - Secret Scholar Society
5 days agoThe Moment Tim Pool Discovered Why Andrew Wilson is so Unstoppable
11.3K19 -
DVR
Film Threat
3 hours agoLIVE FROM SAN DIEGO COMIC-CON! (Thursday) | Film Threat Live
364 -
1:40:00
The Quartering
2 hours agoEpstein Burnout, Hulk Hogan Dies, South Park Flops & Much More
94.9K19 -
10:05
Michael Button
6 hours ago $0.10 earnedGroundbreaking Discovery at Stonehenge Rewrites History
2993 -
LIVE
RalliedLIVE
2 hours ago $2.48 earnedSPECIALIST ADDICTED MAN WINS WARZONE SOLOS
257 watching -
1:11:41
Sean Unpaved
3 hours agoBat Flips to Boardrooms: Jets QB Crossroads, Presidential Visits, & RedZone's TV Takeover
35.5K -
DVR
SportsPicks
3 hours agoCrick's Corner: Episode 51
4.32K -
1:00:45
Russell Brand
5 hours agoUK Migration Clashes ERUPT! Starmer Sweats as ‘SUMMER OF RIOTS’ Begins? - SF620
137K62