Sunday, 16 May 2021

Maximum Size Subarray Sum Equals k

 Given an array nums and a target value k, find the maximum length of a subarray that sums to k. If there isn’t

one, return 0 instead.

Note: The sum of the entire nums array is guaranteed to fit within the 32-bit signed integer range.

Example 1: Given nums = [1, -1, 5, -2, 3], k = 3, return 4. (because the subarray [1, -1, 5, -2] sums to 3 and is the

longest)


public class MaxSizeSubArraySumK {

    public static void main(String[] args) {

        int arr[] = {2,1,-1,3,5,2,-5,1,-3};

        int k = 3;

        int max = 0;

        int sum = 0;

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

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

            sum+=arr[i];


            if(sum==k){

                max = Math.max(max,i);

            }


            int diff = sum-k;


            if(map.containsKey(diff)){

                max= Math.max(max,i-map.get(diff));

            }

            if(!map.containsKey(sum)){

                map.put(sum,i);

            }


        }


        System.out.println(max);

    }


result: 8

No comments:

Post a Comment

links for Data Structure

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