Morgan Stanley Medium csharp

Maximum Subarray

Animated walkthrough

Step through the algorithm visually — use Play or the step buttons (inspired by AlgoMaster / visualgo).

Step 1 / 1

Morgan Stanley interview context: Maximum Subarray is a Medium Greedy problem — Prove greedy choice property — common in scheduling and intervals.

Use the animation above to step through each move before writing code.

Pattern: Greedy

Read from stdin, write to stdout. Classic interview problem #53.

Problem

Maximum Subarray — Morgan Stanley interview prep · Greedy

Classic interview problem #53.

Input (stdin)

Line 1: integers

Output (stdout)

Max subarray sum

Your program must read from stdin and write the answer to stdout (no extra debug text).

Examples

Sample
Input
-2 1 -3 4 -1 2 1 -5 4
Output
6
Hints
  • Input format: Line 1: integers
  • DSA Interview 150 — Greedy
  • Problem #53
  • Frequently asked at Morgan Stanley
  • Greedy

Your solution

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

Solution

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

class Program
{
    static int[] Ria(string line = null)
    {
        line ??= Console.ReadLine();
        if (string.IsNullOrWhiteSpace(line)) return Array.Empty<int>();
        return line.Trim().Split(new[] { ' ', ',', '\t' }, StringSplitOptions.RemoveEmptyEntries)
            .Select(int.Parse).ToArray();
    }
    static string[] Rsa()
    {
        int n = int.Parse(Console.ReadLine());
        var arr = new string[n];
        for (int i = 0; i < n; i++) arr[i] = Console.ReadLine();
        return arr;
    }
    static void W(params object[] parts) => Console.WriteLine(string.Join(" ", parts));
    static void Wb(bool v) => Console.WriteLine(v ? "true" : "false");
    static void Wi(int v) => Console.WriteLine(v);
    static void Ws(string v) => Console.WriteLine(v);

    static void Main()
    {
var nums = Ria();
int best = nums[0], cur = nums[0];
for (int i = 1; i < nums.Length; i++) {
    cur = Math.Max(nums[i], cur + nums[i]);
    best = Math.Max(best, cur);
}
Wi(best);
    }
}

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

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