Given an array containing N integers and an integer K. Your task is to find the length of the longest Sub-Array with sum of the elements equal to the given value K. - Codeprg

Breaking

programing News Travel Computer Engineering Science Blogging Earning

Saturday 4 July 2020

Given an array containing N integers and an integer K. Your task is to find the length of the longest Sub-Array with sum of the elements equal to the given value K.

find the length of the longest Sub-Array with the sum of the elements equal to the given value K.

             find the length of the longest Sub-Array with the sum of the elements equal to the given value K.

Given an array containing N integers and an integer K. Your task is to find the length of the longest Sub-Array with the sum of the elements equal to the given value K.

Example:
Input:
3
6 15
10 5 2 7 1 9
6 -5
-5 8 -14 2 4 12
3 6
-1 2 3
Output:
4
5
0

Input : arr[] = { 10, 5, 2, 7, 1, 9 }, 
K = 15
Output : 4
The sub-array is {5, 2, 7, 1}

#include <bits/stdc++.h>

using namespace std;

int main() {
    int t;
    cin >> t;
    while (t--) {
        int n, m, sum = 0, cnt = 0, f = 0;
        cin >> n >> m;
        int a[n];

        unordered_map < int, int > mp;
        mp[0] = -1;
        for (int i = 0; i < n; ++i) {
            cin >> a[i];
            sum += a[i];
            if (mp.find(sum - m) != mp.end()) {
                cnt = max(cnt, i - mp[sum - m]);
            }

            if (mp.find(sum) == mp.end()) {
                mp[sum] = i;
            }
        }

        cout << cnt << endl;
    }
    return 0;
}