Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K.
If there is no non-empty subarray with sum at least K, return -1.
 



Example 1:
Input: A = [1], K = 1
Output: 1


Example 2:
Input: A = [1,2], K = 4
Output: -1


Example 3:
Input: A = [2,-1,2], K = 3
Output: 3

 
Note:

1 <= A.length <= 50000
-10 ^ 5 <= A[i] <= 10 ^ 5
1 <= K <= 10 ^ 9

```python

USER_FILENAME = "<user_code>"
import sys, json, builtins
import math, heapq, bisect, itertools, functools, collections, statistics, fractions, decimal, operator, array, random, re, string, os, pathlib
try:
    import resource as _res
except Exception:
    _res = None
from collections import Counter, defaultdict, deque, OrderedDict
from functools import lru_cache, reduce
from itertools import accumulate, permutations, combinations, product
from math import gcd, ceil, floor, sqrt
from decimal import Decimal
try:
    from typing import *
except Exception:
    pass
try:
    sys.setrecursionlimit(1_000_000)
except Exception:
    pass
try:
    import site as _site
    try:
        _sys_sites = _site.getsitepackages() if hasattr(_site, "getsitepackages") else []
        for _p in _sys_sites:
            if _p and _p not in sys.path:
                sys.path.append(_p)
    except Exception:
        pass
    try:
        _usp = _site.getusersitepackages()
        if isinstance(_usp, str):
            _usp = [_usp]
        for _p in _usp:
            if _p and _p not in sys.path:
                sys.path.append(_p)
    except Exception:
        pass
except Exception:
    pass

def _disabled_input(*args, **kwargs):
    raise RuntimeError("input() is disabled in callable mode")
builtins.input = _disabled_input

ns = {"__name__": "__judge__"}  # prevent if __name__ == "__main__" blocks
for _k, _v in list(globals().items()):
    if not _k.startswith("_"):
        ns[_k] = _v
_CODE = '# Prepare\n# From @Sarmon:\n# \\"What makes this problem hard is that we have negative values.\n# If you haven\'t already done the problem with positive integers only,\n# I highly recommend solving it first\\"\n\n# Minimum Size Subarray Sum\n\n# Explanation\n# Calculate prefix sum B of list A.\n# B[j] - B[i] represents the sum of subarray A[i] ~ A[j-1]\n# Deque d will keep indexes of increasing B[i].\n# For every B[i], we will compare B[i] - B[d[0]] with K.\n\n\n# Complexity:\n# Every index will be pushed exactly once.\n# Every index will be popped at most once.\n\n# Time O(N)\n# Space O(N)\n\n\n# How to think of such solutions?\n# Basic idea, for array starting at every A[i], find the shortest one with sum at leat K.\n# In my solution, for B[i], find the smallest j that B[j] - B[i] >= K.\n# Keep this in mind for understanding two while loops.\n\n\n# What is the purpose of first while loop?\n# For the current prefix sum B[i], it covers all subarray ending at A[i-1].\n# We want know if there is a subarray, which starts from an index, ends at A[i-1] and has at least sum K.\n# So we start to compare B[i] with the smallest prefix sum in our deque, which is B[D[0]], hoping that [i] - B[d[0]] >= K.\n# So if B[i] - B[d[0]] >= K, we can update our result res = min(res, i - d.popleft()).\n# The while loop helps compare one by one, until this condition isn\'t valid anymore.\n\n\n# Why we pop left in the first while loop?\n# This the most tricky part that improve my solution to get only O(N).\n# D[0] exists in our deque, it means that before B[i], we didn\'t find a subarray whose sum at least K.\n# B[i] is the first prefix sum that valid this condition.\n# In other words, A[D[0]] ~ A[i-1] is the shortest subarray starting at A[D[0]] with sum at least K.\n# We have already find it for A[D[0]] and it can\'t be shorter, so we can drop it from our deque.\n\n\n# What is the purpose of second while loop?\n# To keep B[D[i]] increasing in the deque.\n\n\n# Why keep the deque increase?\n# If B[i] <= B[d.back()] and moreover we already know that i > d.back(), it means that compared with d.back(),\n# B[i] can help us make the subarray length shorter and sum bigger. So no need to keep d.back() in our deque.\n\n\n\n\n\nclass Solution:\n    def shortestSubarray(self, A, K):\n        d = collections.deque([[0, 0]])\n        res, cur = float(\'inf\'), 0\n        for i, a in enumerate(A):\n            cur += a\n            while d and cur - d[0][1] >= K:\n                res = min(res, i + 1 - d.popleft()[0])\n            while d and cur <= d[-1][1]:\n                d.pop()\n            d.append([i + 1, cur])\n        return res if res < float(\'inf\') else -1\n\n                \n'
_co = compile(_CODE, USER_FILENAME, "exec")
exec(_co, ns, ns)

_target = None
_fn_name = 'shortestSubarray'
if _fn_name:
    if "Solution" in ns:
        try:
            _obj = ns["Solution"]()
            if hasattr(_obj, _fn_name):
                _target = getattr(_obj, _fn_name)
        except Exception:
            _target = None
    if _target is None and _fn_name in ns and callable(ns[_fn_name]):
        _target = ns[_fn_name]
# Fallback: if there's exactly one user-defined function, use it
if _target is None:
    _cands = [v for k, v in ns.items() if callable(v) and getattr(v, "__module__", "") in ("__judge__", "__main__")]
    _user_funcs = [c for c in _cands if getattr(c, "__name__", "").startswith("_") is False]
    if len(_user_funcs) == 1:
        _target = _user_funcs[0]
if _target is None:
    raise RuntimeError(f"Could not resolve callable '{_fn_name}'")

_raw = sys.stdin.read().strip()
if _raw:
    _parsed = json.loads(_raw)
    if isinstance(_parsed, dict):
        _kwargs = _parsed.get("kwargs", {})
        _args = _parsed.get("args", [])
    else:
        _args, _kwargs = _parsed, {}
else:
    _args, _kwargs = [], {}
if not isinstance(_args, (list, tuple)):
    _args = [_args]
_res = _target(*_args, **_kwargs)
try:
    sys.stdout.write(repr(_res) + "\n")
except Exception:
    pass

```

Measured memory_bytes: 6528