Longest Subarray with Given Sum (Positives and Negatives) - Optimal Approach

Longest Subarray with Given Sum (Positives and Negatives) - Optimal Approach

Algorithm Steps

  1. Given an array arr of integers (positive, negative, or zero) and a target sum k.
  2. Initialize prefix_sum = 0, max_len = 0, and an empty hash_map to store the first occurrence of each prefix sum.
  3. Iterate through the array with index i:
  4. → Add arr[i] to prefix_sum.
  5. → If prefix_sum == k, update max_len = i + 1.
  6. → If prefix_sum - k exists in hash_map, calculate the length and update max_len accordingly.
  7. → If prefix_sum is not in hash_map, store prefix_sum with index i.
  8. Return max_len after the loop ends.

Longest Subarray with Given Sum using HashMap Code

Python
JavaScript
Java
C++
C
def longest_subarray_with_sum_k(arr, k):
    prefix_sum = 0
    max_len = 0
    prefix_map = {}

    for i in range(len(arr)):
        prefix_sum += arr[i]

        if prefix_sum == k:
            max_len = i + 1

        if (prefix_sum - k) in prefix_map:
            max_len = max(max_len, i - prefix_map[prefix_sum - k])

        if prefix_sum not in prefix_map:
            prefix_map[prefix_sum] = i

    return max_len

# Sample Input
arr = [1, -1, 5, -2, 3]
k = 3
print("Length of Longest Subarray:", longest_subarray_with_sum_k(arr, k))