Advertisement
ntodorova

Arrays - 06_MaximalSum

Jan 14th, 2013
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.43 KB | None | 0 0
  1. using System;
  2.  
  3. /*
  4.  * 6. Write a program that reads two integer numbers N and K and an array of N elements
  5.  * from the console. Find in the array those K elements that have maximal sum.
  6.  */
  7. class MaximalSum
  8. {
  9.     static void Main()
  10.     {
  11.         int n = 6;
  12.         int k = 3;
  13.         int sum = 0;
  14.         int bestSum = sum;
  15.         int tmpIndex = 0;
  16.         int endIndexOfMax = 0;
  17.  
  18.  
  19.         Console.Write("N = ");
  20.         string strN = Console.ReadLine();
  21.  
  22.         Console.Write("K = ");
  23.         string strK = Console.ReadLine();
  24.  
  25.         if (!int.TryParse(strN, out n) || !int.TryParse(strK, out k) || k > n)
  26.         {
  27.             Console.WriteLine("Invalid numbers!");
  28.         }
  29.         else
  30.         {
  31.             int[] array = new int[n];
  32.  
  33.             // Get all array values
  34.             for (int i = 0; i < n; i++)
  35.             {
  36.                 Console.Write("Please enter array element: ");
  37.                 array[i] = int.Parse(Console.ReadLine());
  38.             }
  39.  
  40.             for (int j = 0; j < n - k + 1; j++)
  41.             {
  42.                 for (int p = j; p < k + j; p++)
  43.                 {
  44.                     sum += array[p];
  45.                     tmpIndex = p;
  46.                 }
  47.  
  48.                 if (sum > bestSum)
  49.                 {
  50.                     bestSum = sum;
  51.                     endIndexOfMax = tmpIndex;
  52.                 }
  53.  
  54.                 sum = 0;
  55.             }
  56.  
  57.             Console.WriteLine("The maximal sum of {0} sequent elements is: {1}", k, bestSum);
  58.             Console.Write("{ ");
  59.  
  60.             for (int i = endIndexOfMax - k + 1; i <= endIndexOfMax; i++)
  61.             {
  62.                 if (i == endIndexOfMax)
  63.                 {
  64.                     Console.Write("{0}", array[i]);
  65.                 }
  66.                 else
  67.                 {
  68.                     Console.Write("{0}, ", array[i]);
  69.                 }
  70.             }
  71.  
  72.             Console.WriteLine(" }");
  73.         }
  74.     }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement