How to find the maximum length of a subarray having a sum equal to K in C#

1 Answer

0 votes
using System;
using System.Collections.Generic;

public class Program
{
	internal static int maxSubArrayLenEqualsToK(int[] arr, int k) {
		int current = 0, len = 0;

		Dictionary<int, int> dict = new Dictionary<int, int>(); 
		int size = arr.Length;

		for (int i = 0; i < size; i++) {
			current += arr[i];
			if (current == k) {
				len = i + 1;
			}
			else if (dict.ContainsKey(current - k)) {
				len = Math.Max(len, i - dict[current - k]);
			}
			if (!dict.ContainsKey(current)) {
				dict[current] = i;
			}
		}

		return len;
	}

	public static void Main(string[] args)
	{
		int[] arr = new int[] {1, -1, 5, -2, -3, 2, 3, 3};

		int K = 3;

		// 1, -1, 5, -2 = 3 (4)
		// 5, -2 = 3 (2)
		// -2, -3, 2, 3, 3 = 3 (5)

		Console.Write(maxSubArrayLenEqualsToK(arr, K));
	}
}



/*
run:
 
5
 
*/

 



answered Feb 23, 2024 by avibootz
...