2875. Minimum Size Subarray in Infinite Array

T: O(n)
S: O(n)
```java
class Solution {
    public int minSizeSubarray(int[] nums, int target) {
        int n = nums.length;
        long sum = 0l;

        Map<Long, Integer> map = new HashMap<>();
        map.put(0l, -1);
        
        for (int num : nums) {
            sum += num;
        }

        int k = (int)(target/sum);
        target %= sum;
        if (target == 0) {
            return k*n;
        }
        
        long total = 0l;
        int result = Integer.MAX_VALUE;
        for (int i = 0; i < 2*n; i++) {
            total += nums[i%n];
            
            if (map.containsKey(total - target)) {
                result = Math.min(result, (int)(i - map.get(total - target)));
            }
            map.put(total, i);
        }
        return result == Integer.MAX_VALUE ? -1 : result + k*n;
    }
}
/**

prefix sum
        repeat
   j    k*sum       i
[     ]....  [.    ]
   ------------  traget sum

this question's target is quite large, so we can divide by sum -> 

if target is very big, larger than 2* sum -> in the middle, we can have k*sum

this k*sum -> == k*n distance

if we have this k*n -> now we can focus on (target % sum), then it become the "normal prefix sum and hashmap question"

        Map<Long, Integer> map = new HashMap<>();
        map.put(0l, -1);

        prefix sum        
        ... find max idx diff

at last remember ans is (max result + k*n)
can't find -> return -1

T: O(n)
S: O(n)
*/
```

Last updated