Advertisement
Klaxon

[C# Arrays] Sequence of Maximal Sum

Jul 15th, 2013
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.55 KB | None | 0 0
  1. // 8. 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)? -> Yes!
  4.  
  5. using System;
  6.  
  7. class SequenceOfMaximalSum
  8. {
  9.     static void Main()
  10.     {
  11.         // get the array size
  12.         Console.Write("Enter wanted array size: ");
  13.         int n = int.Parse(Console.ReadLine());
  14.  
  15.         int[] array = new int[n];
  16.  
  17.         // help variables
  18.         int currentSum = 0;
  19.         int maxSum = int.MinValue;
  20.         int startIndex = 0;
  21.         int endIndex = 0;
  22.  
  23.         // main magic
  24.         for (int i = 0; i < n; i++)
  25.         {
  26.             array[i] = int.Parse(Console.ReadLine());
  27.  
  28.             currentSum += array[i];
  29.  
  30.             if (array[i] > currentSum)
  31.             {
  32.                 currentSum = array[i];
  33.                 startIndex = i;
  34.             }
  35.             if (currentSum > maxSum)
  36.             {
  37.                 maxSum = currentSum;
  38.                 endIndex = i;
  39.             }
  40.         }
  41.         Console.WriteLine();
  42.  
  43.         // printing
  44.         Console.Write("{");
  45.         for (int i = startIndex; i <= endIndex; i++)
  46.         {
  47.             if (i == endIndex)
  48.             {
  49.                 Console.Write("{0}", array[i]);
  50.             }
  51.             else
  52.             {
  53.                 Console.Write("{0}, ", array[i]);
  54.             }
  55.         }
  56.         Console.WriteLine("}");
  57.         Console.WriteLine("Maximal sum / number is: {0}", maxSum);
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement