Advertisement
Assi

MaxSumOfElementsK

Jan 6th, 2013
250
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.72 KB | None | 0 0
  1. using System;
  2. using System.Diagnostics;
  3.  
  4.  
  5. class MaxSumOfElementsK
  6. {
  7.     static void Main()
  8.     {
  9.         Console.Write("Enter n=");
  10.         int n = int.Parse(Console.ReadLine());
  11.         Console.Write("Enter k=");                  
  12.         int k = int.Parse(Console.ReadLine());      
  13.         int firstSum = 0;
  14.         int biggestSum = 0;
  15.         int lastSum = 0;
  16.        
  17.         int[] arr = new int [n];
  18.  
  19.         for (int i = 0; i < n; i++)
  20.         {
  21.             Console.Write("Enter arr index [{0}]=",i);
  22.             arr[i] = int.Parse(Console.ReadLine()); //Read number from Console
  23.         }
  24.         Stopwatch chronometer = new Stopwatch();
  25.          chronometer.Start();
  26.         for (int i = 0; i < arr.Length; i++)// changing index of arr
  27.         {
  28.             if (i+k-1 < arr.Length)           // Stop before going out of arr boundry
  29.             {
  30.                
  31.                 if (i==0)                   //Calculating the first sequence k
  32.                 {
  33.                     for (int j = 0; j < k; j++)
  34.                     {
  35.                         firstSum = firstSum + arr[i + j];
  36.                         lastSum = firstSum;
  37.                     }
  38.                    
  39.                 }
  40.                 else                        //Calculating the others sequence
  41.                 {
  42.                     lastSum = (lastSum - arr[i - 1]) + arr[i + k - 1];
  43.                 }
  44.             }
  45.             if (lastSum > biggestSum)      //Putting the biggest sum in variable
  46.             {
  47.                 biggestSum = lastSum;
  48.             }  
  49.         }
  50.         Console.WriteLine("The biggest sum is {0}",biggestSum);
  51.         chronometer.Stop();
  52.         Console.WriteLine(chronometer.Elapsed);
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement