Sunday, 16 May 2021

Subarray Sum Equals K

 Given an array of integers and an integer k, find the total number of continuous subarrays whose sum equals to

k.

Example 1:

Input:nums = [1,1,1], k = 2 Output: 2

Note that empty array is not considered as a subarray.


public class CountSubarraySumEqualsK {

    public static void main(String[] args) {


        int arr[] = {3,9,-2,4,1,-7,2,6,-5,8,-3,-7,6,2,1};

        //int arr[] = {1,1,2};

        Map<Integer,Integer> map= new HashMap<>();

        int sum = 0;

        int count = 0;

        int k = 5;

       // int k =2;

        for(int i = 0;i<arr.length;i++){

            sum+=arr[i];


            if(sum==k){

                count++;

            }


            int diff = sum-k;


            if(map.containsKey(diff)){

                count = count + map.get(diff);

            }


            if(map.containsKey(sum)){

                map.put(sum,map.get(sum)+1);

            }else{

                map.put(sum,1);

            }


        }


        System.out.println(count);

    }

}



Result: 7

No comments:

Post a Comment

links for Data Structure

  1) 𝐁𝐞𝐜𝐨𝐦𝐞 𝐌𝐚𝐬𝐭𝐞𝐫 𝐒𝐧 π‹π’π§π€πžπ 𝐋𝐒𝐬𝐭:  https://lnkd.in/gXQux4zj 2) 𝐀π₯π₯ 𝐭𝐲𝐩𝐞𝐬 𝐨𝐟 π“π«πžπž π“π«πšπ―πžπ«π¬πšπ₯𝐬...