Untitled

 avatar
unknown
plain_text
23 days ago
1.2 kB
2
Indexable
import java.util.TreeMap;

public class ShortestSubarraySum {
    public int shortestSubarray(int[] nums, int k) {
        TreeMap<Long, Integer> prefixMap = new TreeMap<>();
        long prefixSum = 0;
        int minLength = Integer.MAX_VALUE;

        // Initialize TreeMap with prefix sum 0 at index 0
        prefixMap.put(0L, 0);

        for (int i = 0; i < nums.length; i++) {
            prefixSum += nums[i];
            Long target = prefixMap.floorKey(prefixSum - k);
            if (target != null) {
                int index = prefixMap.get(target);
                minLength = Math.min(minLength, i+1 - index);
            }

            // Add current prefix sum to TreeMap/last occurance
            prefixMap.put(prefixSum, i+1);
        }

        return minLength == Integer.MAX_VALUE ? -1 : minLength;
    }

    public static void main(String[] args) {
        ShortestSubarraySum solution = new ShortestSubarraySum();
        System.out.println(solution.shortestSubarray(new int[]{1}, 1)); // Output: 1
        System.out.println(solution.shortestSubarray(new int[]{1, 2}, 4)); // Output: -1
        System.out.println(solution.shortestSubarray(new int[]{2, -1, 2}, 3)); // Output: 3
    }
}
Leave a Comment