<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <em>the length of the shortest non-empty <strong>subarray</strong> of </em><code>nums</code><em> with a sum of at least </em><code>k</code>. If there is no such <strong>subarray</strong>, return <code>-1</code>.</p>

<p>A <strong>subarray</strong> is a <strong>contiguous</strong> part of an array.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> nums = [1], k = 1
<strong>Output:</strong> 1
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> nums = [1,2], k = 4
<strong>Output:</strong> -1
</pre><p><strong class="example">Example 3:</strong></p>
<pre><strong>Input:</strong> nums = [2,-1,2], k = 3
<strong>Output:</strong> 3
</pre>
<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
	<li><code>-10<sup>5</sup> &lt;= nums[i] &lt;= 10<sup>5</sup></code></li>
	<li><code>1 &lt;= k &lt;= 10<sup>9</sup></code></li>
</ul>

typedef long long ll;
typedef pair<ll,ll> ii;
class Solution {
public:
    vector<ll> seg, pref;

    int left(int u) { return u * 2; }
    int right(int u) { return u * 2 + 1; }
    
    void build(int u, int L, int R) {
        if (L == R) seg[u] = pref[L];
        else {
            int mid = (L+R)/2;
            build(left(u), L, mid);
            build(right(u), mid+1, R);
            seg[u] = max(seg[left(u)], seg[right(u)]);
        }
    }

    int search(int u, int L, int R, int i, int j, ll k) {
        if (R < i || j < L || seg[u] < k) return 1e9;
        int mid = (L+R)/2;
        if (i <= L && R <= j) {
            if (L == R) return L;
            else if(seg[left(u)] >= k) return search(left(u), L, mid, i, j, k);
            else return search(right(u), mid+1, R, i, j, k);
        } else {
            int esq = search(left(u), L, mid, i, j, k);
            int dir = search(right(u), mid+1, R, i, j, k);
            return min(esq, dir);
        }
    }

    int shortestSubarray(vector<int>& nums, int k) {
        int n = nums.size();
        seg.assign(4*n + 5, 0);
        pref.assign(n, 0);

        pref[0] = nums[0];
        for(int i = 1; i < n; i++)
            pref[i] += pref[i - 1] + nums[i];
        build(1, 0, n-1);

        int ans = 1e9;
        for(int i = 0; i < n; i++) {
            ll sum =  k + (i-1 >= 0 ? pref[i - 1] : 0);
            int idx = search(1, 0, n-1, i, n-1, sum);
            if (idx != 1e9)
                ans = min(ans, idx - i + 1);
        }

        return (ans == 1e9 ? -1 : ans);
    }
};
130620