Advertisement
Guest User

My algorithm - find the sequence with max sum in array

a guest
Jul 14th, 2013
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.82 KB | None | 0 0
  1. using System;
  2.  
  3. namespace Task_8_SequenceMaxSum
  4. {
  5. class Program
  6. {
  7. static void Main()
  8. {
  9.     int[] Arr = new int[10];
  10.     string input;
  11.     int CurrentSum = 0;
  12.     int MaxSum = 0;
  13.     int MaxSeqLenght = 0;
  14.     int EndPosition = 0;
  15.     int EndPositionMax = 0;
  16.  
  17.     for (int i = 0; i < Arr.Length; i++)
  18.     {
  19.         Console.Write("Please enter element {0} of the array: ", i);
  20.         input = Console.ReadLine();
  21.  
  22.         while (int.TryParse(input, out Arr[i]) == false)
  23.         {
  24.             Console.Write("Please enter a valid integer!: ");
  25.             input = Console.ReadLine();
  26.         }
  27.     }
  28.  
  29.     for (int CountOfElements = 2; CountOfElements <= Arr.Length; CountOfElements++)     //Increase number of elements to sum in every loop
  30.     {
  31.         for (int StartPosition = 0; StartPosition <= Arr.Length - CountOfElements; StartPosition++) //Move the start position in every loop
  32.         {
  33.             for (int i = 0; i < CountOfElements; i++)       //Calculate every sum
  34.             {
  35.                 CurrentSum += Arr[StartPosition + i];
  36.                 EndPosition = StartPosition + i;
  37.             }
  38.             if (CurrentSum > MaxSum)                        //Check every sum if there is a bigger one
  39.             {
  40.                 MaxSum = CurrentSum;
  41.                 MaxSeqLenght = CountOfElements;
  42.                 EndPositionMax = EndPosition;
  43.             }
  44.             CurrentSum = 0;         //Restart the current sum
  45.         }
  46.         CurrentSum = 0;
  47.     }
  48.    
  49.     //Now print the elements
  50.     Console.Write("The sequence with max sum is: { ");
  51.     for (int i = EndPositionMax - MaxSeqLenght + 1; i <= EndPositionMax; i++)
  52.     {
  53.         Console.Write(Arr[i] + " ");
  54.     }
  55.     Console.Write("}");
  56.     Console.WriteLine(MaxSeqLenght + " elements");
  57.     Console.WriteLine("Max Sum: " + MaxSum);
  58. }
  59. }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement