Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public int minSumOfLengths(int[] nums, int target) {
- Map<Integer, Integer> sums = new HashMap<>(); // prefix sum, index
- sums.put(0, -1);
- int sum = 0; // prefix sum
- for (int i = 0; i < nums.length; i++) {
- sum += nums[i];
- sums.put(sum, i);
- // store prefix sums to nums for the second loop
- nums[i] = sum;
- }
- int ans = Integer.MAX_VALUE;
- int len1 = Integer.MAX_VALUE;
- for (int i = 0; i < nums.length; i++) {
- // Find minimum length of subarray ends at index <= i
- if (sums.containsKey(nums[i] - target)) {
- len1 = Math.min(len1, i - sums.get(nums[i] - target));
- }
- // Find length of subarray starts at index <= i
- if (sums.containsKey(nums[i] + target) && len1 < Integer.MAX_VALUE) {
- int len2 = sums.get(nums[i] + target) - i;
- ans = Math.min(ans, len1 + len2);
- }
- }
- return ans == Integer.MAX_VALUE ? -1 : ans;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement