AtCoderの企業コンテスト    次の企業コンテストの問題へ    前の企業コンテストの問題へ

Donuts プロコンチャレンジ2014 C ソーシャルゲーム


問題へのリンク


C#のソース

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

class Program
{
    static string InputPattern = "InputX";

    static List<string> GetInputList()
    {
        var WillReturn = new List<string>();

        if (InputPattern == "Input1") {
            WillReturn.Add("7");
            WillReturn.Add("3 -4 2 3 -1 2 -1");
            //6
        }
        else if (InputPattern == "Input2") {
            WillReturn.Add("3");
            WillReturn.Add("10 20 30");
            //60
        }
        else if (InputPattern == "Input3") {
            WillReturn.Add("3");
            WillReturn.Add("-4 -2 -5");
            //-2
        }
        else {
            string wkStr;
            while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
        }
        return WillReturn;
    }

    static long[] GetSplitArr(string pStr)
    {
        return (pStr == "" ? new string[0] : pStr.Split(' ')).Select(pX => long.Parse(pX)).ToArray();
    }

    static void Main()
    {
        List<string> InputList = GetInputList();
        long[] AArr = GetSplitArr(InputList[1]);

        if (Array.TrueForAll(AArr, pX => pX < 0)) {
            Console.WriteLine(AArr.Max());
            return;
        }

        var AnswerList = new List<long>();
        long RunSum = 0;
        foreach (long EachA in AArr) {
            RunSum += EachA;
            AnswerList.Add(RunSum);
            RunSum = Math.Max(0, RunSum);
        }
        Console.WriteLine(AnswerList.Max());
    }
}


解説

自由な場所から開始可能な累積和での最大値なので
カダンのアルゴリズムで解けます。