Medium csharp

Maximum subarray sum (Kadane) #50

Problem

Find max contiguous subarray sum for array with values 1..6 and one negative.

Hints
  • cur = max(a[k], cur + a[k])

Your solution

TestStatusDetails
Ready — edit the code above and click Run or Submit.

Solution

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        int[] a = { 1, 2, 3, 4, 5, 6, -6 };
        int best = a[0], cur = a[0];
        for (int k = 1; k < a.Length; k++) {
            cur = Math.Max(a[k], cur + a[k]);
            best = Math.Max(best, cur);
        }
        Console.WriteLine(best);
    }
}

Try solving on your own first, then reveal the official answer.

Explanation

Kadane's algorithm for max subarray.

Discussion

0

Sign in to join the discussion.

No discussions yet — ask the first question!

Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details