➤ Java Bean with Examples
➤ How to Code a Game
➤ Array Programs in Java
➤ Java Inline Thread Creation
➤ Java Custom Exception
➤ Hibernate vs JDBC
➤ Object Relational Mapping
➤ Check Oracle DB Size
➤ Check Oracle DB Version
➤ Generation of Computers
➤ XML Pros & Cons
➤ Git Analytics & Its Uses
➤ Top Skills for Cloud Professional
➤ How to Hire Best Candidates
➤ Scrum Master Roles & Work
➤ CyberSecurity in Python
➤ Protect from Cyber-Attack
➤ Solve App Development Challenges
➤ Top Chrome Extensions for Twitch Users
➤ Mistakes That Can Ruin Your Test Metric Program
➤ How to Code a Game
➤ Array Programs in Java
➤ Java Inline Thread Creation
➤ Java Custom Exception
➤ Hibernate vs JDBC
➤ Object Relational Mapping
➤ Check Oracle DB Size
➤ Check Oracle DB Version
➤ Generation of Computers
➤ XML Pros & Cons
➤ Git Analytics & Its Uses
➤ Top Skills for Cloud Professional
➤ How to Hire Best Candidates
➤ Scrum Master Roles & Work
➤ CyberSecurity in Python
➤ Protect from Cyber-Attack
➤ Solve App Development Challenges
➤ Top Chrome Extensions for Twitch Users
➤ Mistakes That Can Ruin Your Test Metric Program
Stack, Queue, and Deque Problems | Also see:- Bit Manipulation and Math DSA Problems, Array DSA Problems, Binary Search DSA Problems, Sliding Windows and Two Pointers
Table of Contents
1. 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. Problem: 862
class Solution {
public int shortestSubarray(int[] nums, int k) {
int n = nums.length, res = Integer.MAX_VALUE;
long[] prefixSum = new long[n+1];
for(int i=0; i<n; i++){
prefixSum[i+1] = prefixSum[i] + nums[i];
}
Deque<Integer> deque = new LinkedList<>();
for(int i=0; i<=n; i++){
while(!deque.isEmpty() && prefixSum[i] - prefixSum[deque.peekFirst()] >= k){
res = Math.min(res, i - deque.pollFirst());
}
while(!deque.isEmpty() && prefixSum[i] <= prefixSum[deque.peekLast()]){
deque.pollLast();
}
deque.addLast(i);
}
return res == Integer.MAX_VALUE ? -1 : res;
}
}
If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!