SHARE
TWEET

Exercise08SequenceOfMaximalSum

g-stoyanov Jan 9th, 2013 188 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. public class Exercise08SequenceOfMaximalSum
  6. {
  7.     public static void Main()
  8.     {
  9.         int maxStart = 0;
  10.         int start = 0;
  11.         int maxEnd = 0;
  12.         int maxSum = 0;
  13.         int sum = 0;
  14.         Console.Write("Please input array, with white space for separator between elements: ");
  15.         List<int> array = Console.ReadLine().Split(' ').Select(int.Parse).ToList();
  16.         if (array.TrueForAll(x => x <= 0))
  17.         {
  18.             Console.WriteLine("\n" + array.Max());
  19.         }
  20.         else
  21.         {
  22.             for (int i = 0; i < array.Count; i++)
  23.             {
  24.                 sum = sum + array[i];
  25.                 if (sum > maxSum)
  26.                 {
  27.                     maxSum = sum;
  28.                     maxStart = start;
  29.                     maxEnd = i;
  30.                 }
  31.  
  32.                 if (sum < 0)
  33.                 {
  34.                     start = i + 1;
  35.                     sum = 0;
  36.                 }
  37.             }
  38.  
  39.             Console.WriteLine("\n");
  40.             for (int i = maxStart; i <= maxEnd; i++)
  41.             {
  42.                 Console.Write(array[i] + " ");
  43.             }
  44.         }
  45.  
  46.         Console.WriteLine("\n");
  47.     }
  48. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top