[Java] Sliding Window with dp, O(N), 20 lines
This problem is similar to 560. Subarray Sum Equals K\n\nLike Subarray Sum Equals K we use HashMap to remember the prefix sum, here we choose sum - target as ou
This problem is similar to [560. Subarray Sum Equals K](https://leetcode.com/problems/subarray-sum-equals-k/discuss/?currentPage=1&orderBy=most_votes&query=)\n\nLike `Subarray Sum Equals K` we use `HashMap` to remember the prefix sum, here we choose `sum - target` as our key and `index` as value, so `length = i - map.get(sum - target)`. In case the first x element\'s sum equals `target` we should put `(0 , -1)` first.\n\nSince we need to calculate the length of two sub-arrays, we can use dp to memorize the minimum length of previous subarray.\n\n```\nclass Solution {\n    public int minSumOfLengths(int[] arr, int target) {\n        HashMap<Integer, Integer> map = new HashMap<>();\n        int sum = 0;\n        map.put(0, -1);\n        int[] min = new int[arr.length];\n        int res = Integer.MAX_VALUE;\n        for (int i = 0; i < arr.length; i++) {\n            sum += arr[i];\n            min[i] = i > 0? min[i - 1] : Integer.MAX_VALUE;\n            if (map.containsKey(sum - target)) {\n                int pre = map.get(sum - target);\n                min[i] = Math.min(min[i], i - pre);\n\t\t\t\t// if pre equals -1 means we only get one sub-array whoes sum eqauls target\n                if (pre != -1 && min[pre] != Integer.MAX_VALUE) {\n                    res = Math.min(res, min[pre] + i - pre);\n                }\n            }\n            map.put(sum, i);\n        }\n        return res == Integer.MAX_VALUE ? -1 : res;\n    }\n}\n```
[]