Maximum Subarray Sum

Spread the love

Input: arr[] = {2, 3, -8, 7, -1, 2, 3}
Output: 11
Explanation: The subarray {7, -1, 2, 3} has the largest sum 11.

Input: arr[] = {-2, -4}
Output: –2
Explanation: The subarray {-2} has the largest sum -2.

Input: arr[] = {5, 4, 1, 7, 8}
Output: 25
Explanation: The subarray {5, 4, 1, 7, 8} has the largest sum 25.

// C# Program to find the maximum subarray sum using nested loops

using System;

class GfG {

// Function to find the sum of subarray with maximum sum
static int MaxSubarraySum(int[] arr) {
    int res = arr[0];

    // Outer loop for starting point of subarray
    for (int i = 0; i < arr.Length; i++) {
        int currSum = 0;

        // Inner loop for ending point of subarray
        for (int j = i; j < arr.Length; j++) {
            currSum = currSum + arr[j];

            // Update res if currSum is greater than res
            res = Math.Max(res, currSum);
        }
    }
    return res;
}

static void Main() {
    int[] arr = {2, 3, -8, 7, -1, 2, 3};
    Console.WriteLine(MaxSubarraySum(arr));
}

}

Leave a Comment

Your email address will not be published. Required fields are marked *

https://www.cooljerseyedge.com, https://www.collegeshopfan.com, https://www.kcchiefsgearusa.com, https://www.dlionsgearusa.com, https://www.bravensgearusa.com, https://www.cbengalsgearusa.com, https://www.gbpackersgearusa.com, https://www.htexansgearusa.com, https://www.laramsgearusa.com, Josh Allen Wyoming Jersey, https://www.dcowboysgearusa.com, https://www.mdolphinsgearusa.com, https://www.aliexfanshop.com, https://www.bestplayershop.com, https://www.collegeedgeshop.com, https://www.giantsonlinefans.com