-
-
Save zaidw21/66d3cff276ba8ffd6d42cfc64b1dc70f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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