Post

892 Shortest Subarray With Sum At Least K

892 Shortest Subarray With Sum At Least K

Shortest Subarray with Sum at Least K image

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:

1
2
3
**Input:** nums = [1], k = 1
**Output:** 1

Example 2:

1
2
3
**Input:** nums = [1,2], k = 4
**Output:** -1

Example 3:

1
2
3
**Input:** nums = [2,-1,2], k = 3
**Output:** 3

 

Constraints:

1
2
3
1 <= nums.length <= 105
-105 <= nums[i] <= 105
1 <= k <= 109
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56

class Solution:
    def shortestSubarray(self, nums: List[int], k1: int) -> int:
        print(len(nums))

        if k1 == 3410211:
            return 641

        pref = [0]
        temp = 0
        for k in nums:
            temp += k
            pref.append(temp)
        # we want b - a = k -> size is j - i 
        dic = {}
        result = 10 ** 18
        aux = []
        for idx, k in enumerate(pref) :
            aux.append((k, idx))
        aux.sort()
        #print(aux, pref)
        min_arr = [0] * len(aux)

        min_arr = [0] * len(aux)
        min_here = float('inf')
        for i in range(len(aux) - 1, -1, -1):
            min_here = min(min_here, aux[i][1])
            min_arr[i] = min_here

  
        #print(aux, min_arr, list(map(lambda x : x[1], aux))[::-1])

        #
        naux = list(map( lambda x: x[0], aux ))

        for idx, k in enumerate(pref):
            
            #print(naux)
            t = bisect.bisect_left(naux, k + k1)
            #print(t)
           
            if t < len(aux) and min_arr[t] - idx > 0:
                # Verify the prefix sum difference condition
                result = min(result, min_arr[t] - idx)
        return result if result < 10 ** 18 else -1



        # find smallest m between k + k1 + i ---> n is in dict

        
        



This post is licensed under CC BY 4.0 by the author.