Advertisement
exmkg

Untitled

Sep 28th, 2024
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.66 KB | None | 0 0
  1. class Solution {
  2.     public int shortestSubarray(int[] A, int K) {
  3.         int N = A.length;
  4.         int res = N + 1;
  5.  
  6.         long[] B = new long[N + 1];
  7.         for (int i = 0; i < N; i++) {
  8.             B[i + 1] = B[i] + A[i];
  9.         }
  10.  
  11.         Deque<Integer> d = new ArrayDeque<>();
  12.         for (int i = 0; i < N + 1; i++) {
  13.             while (d.size() > 0 && B[i] - B[d.getFirst()]  >=  K) {
  14.                 res = Math.min(res, i - d.pollFirst());
  15.             }
  16.             while (d.size() > 0 && B[i] <= B[d.getLast()]) {
  17.                 d.pollLast();
  18.             }
  19.             d.addLast(i);
  20.         }
  21.         return res <= N ? res : -1;
  22.     }
  23. }
  24.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement