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
Flyover Conservatives
20 hours agoThe Great Gold Cover-Up: Is Fort Knox EMPTY?! - Clay Clark + Dr. Kirk Elliott | FOC Show
1,869 watching -
DVR
Kim Iversen
4 hours agoJeffrey Sachs Just Exposed the Truth They Don’t Want You to Hear
25.4K31 -
2:11:32
Glenn Greenwald
2 hours agoGlenn From Moscow: Russia Reacts to Trump; Michael Tracey Debates Ukraine War | SYSTEM UPDATE #413
35.7K32 -
LIVE
Slightly Offensive
2 hours ago $2.41 earnedGOV. RAMASWAMY? Vivek to import 1 BILLION INDIANS to OHIO | Nightly Offensive
1,114 watching -
4:51:08
Wahzdee
6 hours agoSniper Elite Then Extraction Games—No Rage Challenge! 🎮🔥 - Tuesday Solos
52.8K3 -
2:12:58
Robert Gouveia
5 hours agoSenator's Wife EXPOSED! Special Counsel ATTACKS; AP News BLOWN OUT
61.5K39 -
55:07
LFA TV
1 day agoDefending the Indefensible | TRUMPET DAILY 2.25.25 7PM
26.1K13 -
6:09:26
Barry Cunningham
11 hours agoTRUMP DAILY BRIEFING - WATCH WHITE HOUSE PRESS CONFERENCE LIVE! EXECUTIVE ORDERS AND MORE!
70.2K46 -
1:46:37
Game On!
6 hours ago $3.16 earnedPUMP THE BRAKES! Checking Today's Sports Betting Lines!
36.7K2 -
1:27:21
Redacted News
6 hours agoBREAKING! SOMETHING BIG IS HAPPENING AT THE CIA AND FBI RIGHT NOW, AS KASH PATEL CLEANS HOUSE
183K221