Skip to content

Instantly share code, notes, and snippets.

@zaidw21
Created July 17, 2019 14:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zaidw21/66d3cff276ba8ffd6d42cfc64b1dc70f to your computer and use it in GitHub Desktop.
Save zaidw21/66d3cff276ba8ffd6d42cfc64b1dc70f to your computer and use it in GitHub Desktop.
package com.sgcib.bars.controller;
import java.util.HashMap;
public class Test {
public static void main(String[] args) {
int arr[] = { 10, 2, -2, -20, 10 };
int sum = -10;
int n = arr.length;
System.out.println(findSubarraySum(arr, n, sum));
}
static int findSubarraySum(int arr[], int n, int sum) {
HashMap<Integer, Integer> prevSum = new HashMap<>();
int res = 0;
int currsum = 0;
for (int i = 0; i < n; i++) {
currsum += arr[i];
if (currsum == sum)
res++;
if (prevSum.containsKey(currsum - sum))
res += prevSum.get(currsum - sum);
Integer count = prevSum.get(currsum);
if (count == null)
prevSum.put(currsum, 1);
else
prevSum.put(currsum, count + 1);
}
return res;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment