|
| 1 | +package hashing; |
| 2 | + |
| 3 | +import java.util.HashMap; |
| 4 | +import java.util.Map; |
| 5 | + |
| 6 | +/** |
| 7 | + * Created by gouthamvidyapradhan on 18/10/2017. |
| 8 | + * Given an array nums and a target value k, find the maximum length of a subarray that sums to k. If there isn't |
| 9 | + * one, return 0 instead. |
| 10 | +
|
| 11 | + Note: |
| 12 | + The sum of the entire nums array is guaranteed to fit within the 32-bit signed integer range. |
| 13 | +
|
| 14 | + Example 1: |
| 15 | + Given nums = [1, -1, 5, -2, 3], k = 3, |
| 16 | + return 4. (because the subarray [1, -1, 5, -2] sums to 3 and is the longest) |
| 17 | +
|
| 18 | + Example 2: |
| 19 | + Given nums = [-2, -1, 2, 1], k = 1, |
| 20 | + return 2. (because the subarray [-1, 2] sums to 1 and is the longest) |
| 21 | +
|
| 22 | + Follow Up: |
| 23 | + Can you do it in O(n) time? |
| 24 | + */ |
| 25 | +public class MaximumSizeSubarraySumEqualsk { |
| 26 | + |
| 27 | + /** |
| 28 | + * Main method |
| 29 | + * @param args |
| 30 | + * @throws Exception |
| 31 | + */ |
| 32 | + public static void main(String[] args) throws Exception{ |
| 33 | + int[] A = {1,-1,5,-2,3}; |
| 34 | + System.out.println(new MaximumSizeSubarraySumEqualsk().maxSubArrayLen(A, 10)); |
| 35 | + } |
| 36 | + |
| 37 | + public int maxSubArrayLen(int[] nums, int k) { |
| 38 | + Map<Long, Integer> index = new HashMap<>(); |
| 39 | + long sum = 0L; |
| 40 | + for(int i = 0; i < nums.length; i ++){ |
| 41 | + sum += nums[i]; |
| 42 | + index.putIfAbsent(sum, i); |
| 43 | + } |
| 44 | + sum = 0; |
| 45 | + int ans = 0; |
| 46 | + for(int i = 0; i < nums.length; i ++){ |
| 47 | + sum += nums[i]; |
| 48 | + if(sum == k){ |
| 49 | + ans = Math.max(ans, i + 1); |
| 50 | + } else{ |
| 51 | + long exp = sum - k; |
| 52 | + if(index.containsKey(exp)){ |
| 53 | + int farLeft = index.get(exp); |
| 54 | + if(farLeft < i){ |
| 55 | + ans = Math.max(ans, i - index.get(exp)); |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + return ans; |
| 62 | + } |
| 63 | + |
| 64 | +} |
0 commit comments