archangelmihail

MaximalSumInArray

Dec 19th, 2013
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.16 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. class MaximalSumInArray
  4. {
  5.     static void Main()
  6.     {
  7.         /*  Write a program that finds the sequence of maximal sum in given array. */
  8.         string inputArray = Console.ReadLine();
  9.         char[] delimiter = new char[] { ',', ' ' };
  10.         string[] input = inputArray.Split(delimiter, StringSplitOptions.RemoveEmptyEntries);
  11.         int[] arr = new int[input.Length];
  12.         for (int i = 0; i < input.Length; i++)
  13.         {
  14.             arr[i] = int.Parse(input[i]);
  15.         }
  16.         List<int> subset = new List<int>();
  17.         string result = "";
  18.         int maxSum = 0;
  19.         int currentSum = 0;
  20.         for (int i = 0; i < arr.Length; i++)
  21.         {
  22.             subset.Add(arr[i]);
  23.             currentSum += arr[i];
  24.             if (currentSum > maxSum)
  25.             {
  26.                 maxSum = currentSum;
  27.             }
  28.             else if (currentSum < 0)
  29.             {
  30.                 currentSum = 0;
  31.                 subset.Clear();
  32.             }
  33.         }
  34.         result = "{" + string.Join(",", subset) + "}";
  35.         Console.WriteLine(result);
  36.         Console.WriteLine(maxSum);
  37.     }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment