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;
}
};
-
4:40
GritsGG
12 hours agoTwo Easter Eggs on Call of Duty Warzone!
7.42K1 -
2:08:19
Side Scrollers Podcast
19 hours agoNetflix Execs to TESTIFY Over LGBTQ Agenda + IGN DESTROYS Xbox Game Pass + More | Side Scrollers
56.1K14 -
5:08:55
Dr Disrespect
17 hours ago🔴LIVE - DR DISRESPECT - BABY STEPS - THE VERY VERY LAST CHAPTER
124K17 -
10:28
BlabberingCollector
13 hours agoAsk Blabs, Episode 5 | Answering Your Wizarding World Related Questions
7.93K1 -
18:09
Forrest Galante
5 days agoI Survived 24 Hours In The World's Deadliest Jungle
187K30 -
LIVE
Lofi Girl
2 years agoSynthwave Radio 🌌 - beats to chill/game to
318 watching -
2:15:09
Badlands Media
17 hours agoOnlyLands Ep. 27: Power Hour Hangover, Trump’s Wartime Shift, and Portland in Flames
113K26 -
22:21
DeVory Darkins
7 hours ago $17.63 earnedRioters attack Portland ICE Facility as Democrats make shocking admission
22.8K87 -
2:06:06
TimcastIRL
10 hours agoTrump DOJ Announces INTERVENTION In Portland Over Nick Sortor Arrest | Timcast IRL
238K388 -
6:53:58
SpartakusLIVE
11 hours ago#1 All-American HERO with LUSCIOUS hair and AVERAGE forehead brings Friday Night HYPE
68.9K7