862. Shortest Subarray with Sum at Least K
Difficulty: Hard
Topics: Array, Binary Search, Queue, Sliding Window, Heap (Priority Queue), Prefix Sum, Monotonic Queue
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:
Example 2:
Example 3:
Constraints:
Solution:
We need to use a sliding window approach combined with prefix sums and a monotonic queue. Here's the step-by-step approach:
Prefix Sum:
Monotonic Queue:
Sliding Window Logic:
Let's implement this solution in PHP: 862. Shortest Subarray with Sum at Least K
Explanation:
Prefix Sum Array:
- We compute the cumulative sum of the array in the prefix_sum array. This helps in calculating the sum of any subarray nums[i...j] by using the formula prefix_sum[j 1] - prefix_sum[i].
Monotonic Queue:
- The deque holds indices of the prefix_sum array in increasing order of values. We maintain this order so that we can efficiently find the smallest subarray whose sum is greater than or equal to k.
Sliding Window Logic:
- As we traverse through the prefix_sum array, we try to find the smallest subarray using the difference between the current prefix_sum[i] and previous prefix_sum[deque[0]].
- If the difference is greater than or equal to k, we calculate the subarray length and update the minimum length found.
Returning Result:
- If no valid subarray is found, return -1. Otherwise, return the minimum subarray length.
Time Complexity:
This approach ensures that the solution runs efficiently even for large inputs.
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
The above is the detailed content of . Shortest Subarray with Sum at Least K. For more information, please follow other related articles on the PHP Chinese website!