0% found this document useful (0 votes)
17 views1 page

Longest Subarray with Sum K in C++

The document contains a C++ program that finds the length of the longest subarray with a sum equal to a given value K using prefix sums and a hash map. It maintains a map to track the first occurrence of each prefix sum and updates the maximum length whenever a valid subarray is found. The main function demonstrates the usage of this algorithm with a sample array and target sum.

Uploaded by

23cs98
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views1 page

Longest Subarray with Sum K in C++

The document contains a C++ program that finds the length of the longest subarray with a sum equal to a given value K using prefix sums and a hash map. It maintains a map to track the first occurrence of each prefix sum and updates the maximum length whenever a valid subarray is found. The main function demonstrates the usage of this algorithm with a sample array and target sum.

Uploaded by

23cs98
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

// C++ Program: Longest Subarray with Sum = K using Prefix Sum + Hash Map

#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;

int longestSubarrayWithSumK(vector<int>& nums, int k) {


unordered_map<int, int> prefixMap; // prefixSum -> firstIndex
int maxLen = 0, currSum = 0;

for (int i = 0; i < [Link](); i++) {


currSum += nums[i];

// If prefix sum equals k


if (currSum == k) {
maxLen = i + 1;
}

// If (currSum - k) is found in map


if ([Link](currSum - k) != [Link]()) {
int len = i - prefixMap[currSum - k];
maxLen = max(maxLen, len);
}

// Store only first occurrence of prefix sum


if ([Link](currSum) == [Link]()) {
prefixMap[currSum] = i;
}
}

return maxLen;
}

int main() {
vector<int> arr = {1, 2, 3, -1, 1, 4};
int k = 10;

int result = longestSubarrayWithSumK(arr, k);


cout << "Length of the longest subarray: " << result << endl;

return 0;
}

You might also like