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;
}
};
-
DVR
iCkEdMeL
1 hour agoBOMBSHELL: Shooter’s Trans Partner Helped Take Him Down
9.75K8 -
1:42:45
The Big Migâ„¢
6 hours agoThe Islamic Invasion – The EU Has Fallen, A Warning For The USA |EP653
20.3K23 -
LIVE
Joker Effect
1 hour agoRUMBLE IN THE DEN 4 - Hungry fighters and NFL legend fight for respect
583 watching -
44:37
Rebel News
2 hours ago🔴 LIVE NOW: Massive ‘Unite the Kingdom’ Rally in London ft. Tommy Robinson | UKrebels.com
26.2K34 -
17:22
Professor Nez
2 hours ago💣BOMBSHELL: The Biden AutoPen Scandal JUST GOT REAL!
4.22K12 -
2:20:03
I_Came_With_Fire_Podcast
10 hours agoRevelations from the Ukrainian Front Lines
27.5K2 -
52:56
X22 Report
6 hours agoMr & Mrs X - Big Pharma Vaccine/Drug Agenda Is Being Exposed To The People - Ep 7
85.3K50 -
1:41:59
THE Bitcoin Podcast with Walker America
11 hours ago $17.40 earnedThe Assassination of Charlie Kirk | Walker America, American Hodl, Erik Cason, Guy Swann
69K37 -
21:33
marcushouse
6 hours ago $1.19 earnedSpaceX Just Revealed the Plan for Starship Flight 11! 🚀
29.5K9 -
35:03
Clownfish TV
9 hours ago'Live by the Sword, Die by the Sword.' | Clownfish TV
34.5K84