SHARE
TWEET

08. MaxSumSeq

Teodor92 Jan 6th, 2013 654 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* Write a program that finds the sequence of maximal sum in given array. Example:
  2.         {2, 3, -6, -1, 2, -1, 6, 4, -8, 8}  {2, -1, 6, 4}
  3.         Can you do it with only one loop (with single scan through the elements of the array)?
  4.  */
  5.  
  6. using System;
  7. using System.Text;
  8.  
  9. class MaxSequence
  10. {
  11.     static void Main()
  12.     {
  13.         int[] myArray = { 2, 3, -6, 36, 12, -1, 6, 4, -8, 8 };
  14.         int currentSum = 0;
  15.         int bestSum = int.MinValue;
  16.         StringBuilder bestSequenceBuild = new StringBuilder();
  17.         string bestSequnce = "";
  18.         for (int i = 0; i < myArray.Length; i++)
  19.         {
  20.             currentSum = currentSum + myArray[i];
  21.             bestSequenceBuild.AppendFormat("{0}, ", myArray[i]);
  22.             if (currentSum > bestSum)
  23.             {
  24.                 bestSum = currentSum;
  25.                 bestSequnce = bestSequenceBuild.ToString();
  26.             }
  27.             if (currentSum < 0)
  28.             {
  29.                 currentSum = 0;
  30.                 bestSequenceBuild.Clear();
  31.             }
  32.         }
  33.         Console.WriteLine("The best sequence is: \" {0} \" ", bestSequnce);
  34.         Console.WriteLine("The best sum is: {0} ", bestSum);
  35.     }
  36. }
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