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
Winston Marshall
1 hour ago“World War II is the founding myth of the modern world” The End Of The World War II Consensus
428 watching -
LIVE
StoneMountain64
42 minutes agoHacker Hunting in Ranked Warzone for the 1st time
482 watching -
LIVE
SpartakusLIVE
2 hours agoVerdansk Ranked with @StoneMountain64 || #1 Morning MACHINE is BACK, Halo later
53 watching -
DVR
Simply Bitcoin
2 hours ago $1.78 earnedBREAKING: Blackrock JUST DROPPED A $600T BOMBSHELL | EP 1268
7.16K -
LIVE
Akademiks
2 hours agoDiddy Trial Day 25: Brendan Paul aka Diddy Dr*g Mule to take the stand. 1 More Witness left. 2/30
2,094 watching -
1:04:44
Timcast
2 hours agoTrump DENIES Peace Talks With Iran, Polymarket Says US WILL Intervene
125K106 -
LIVE
The Charlie Kirk Show
1 hour agoWar, or Peace? + No Kings Aftermath | Sen. Mullin, Friedman | 6.17.25
3,882 watching -
1:58:53
Steven Crowder
4 hours ago🔴 Border Czar Tom Homan Joins Crowder: Will Trump Actually Fulfill Deportation Promises
321K208 -
LIVE
LFA TV
14 hours agoLFA TV ALL DAY STREAM - TUESDAY 6/17/25
2,699 watching -
LIVE
Flyover Conservatives
13 hours agoImplications of US/ISRAEL/IRAN Escalation on Precious Metals - Dr. Kirk Elliott; Big Pharma’s Youngest Customers: The Rise of Medicated Childhood - Joy Pullmann | FOC Show
357 watching