How to find the maximum sum of a subarray in C#

1 Answer

0 votes
using System;

public class Program
{
	public static int maxSubArray(int[] arr) {
		int maxSum = int.MinValue;
		int currentSum = 0;
		int size = arr.Length;

		for (int i = 0; i < size; i++) {
			currentSum = Math.Max(arr[i], currentSum + arr[i]);
			maxSum = Math.Max(currentSum, maxSum);
		}

		return maxSum;
	}

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

		Console.WriteLine(maxSubArray(arr));
	}
}




/*
run:
 
7
 
*/

 



answered Feb 25, 2024 by avibootz
...