Advertisement
Krissy

06. MaxSumKElements

Jan 6th, 2013
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.99 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6.  
  7. class kElementsMaxSum
  8. {
  9.     static void Main()
  10.     {
  11.         int sizeOfArray ;
  12.         int kElements;
  13.        
  14.         do
  15.         {
  16.             Console.WriteLine("Please enter the N number of elements in your array:");
  17.             sizeOfArray = int.Parse(Console.ReadLine());
  18.             Console.WriteLine("Please enter the K number of elements \n,to search their max sum:");
  19.             kElements = int.Parse(Console.ReadLine());
  20.         }
  21.         while (kElements > sizeOfArray || kElements <= 0 || sizeOfArray <= 0);
  22.        
  23.         int[] Array = new int[sizeOfArray];
  24.         int currentSum = 0;
  25.         int maxSum = int.MinValue;
  26.         int currentLen = 0;
  27.         int lastPositionMaxSumElement=0;  
  28.  
  29.         for (int i = 0; i < sizeOfArray; i++)
  30.         {
  31.             Console.WriteLine("Please enter the elements for the array:");
  32.             Array[i] = int.Parse(Console.ReadLine());
  33.                  
  34.                     currentSum += Array[i];
  35.                     currentLen++;
  36.                
  37.                 if (kElements==currentLen)
  38.                 {
  39.                     if (currentSum > maxSum)
  40.                     {
  41.                         maxSum = currentSum;
  42.                         lastPositionMaxSumElement = i;
  43.                     }
  44.  
  45.                     currentLen = kElements-1;
  46.                     currentSum = currentSum-Array[i-kElements+1] ;
  47.                 }        
  48.         }
  49.         Console.WriteLine("The max sum of {0} elements is:{1}", kElements, maxSum);
  50.         Console.Write("The elements are: {");
  51.  
  52.         for (int i = lastPositionMaxSumElement - kElements + 1; i <= lastPositionMaxSumElement; i++)
  53.         {
  54.             if (i == lastPositionMaxSumElement)
  55.             {
  56.                 Console.WriteLine(Array[i] + "}");
  57.             }
  58.             else
  59.             {
  60.                 Console.Write(Array[i] + ", ");
  61.             }
  62.         }
  63.     }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement