Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Diagnostics;
- class MaxSumOfElementsK
- {
- static void Main()
- {
- Console.Write("Enter n=");
- int n = int.Parse(Console.ReadLine());
- Console.Write("Enter k=");
- int k = int.Parse(Console.ReadLine());
- int firstSum = 0;
- int biggestSum = 0;
- int lastSum = 0;
- int[] arr = new int [n];
- for (int i = 0; i < n; i++)
- {
- Console.Write("Enter arr index [{0}]=",i);
- arr[i] = int.Parse(Console.ReadLine()); //Read number from Console
- }
- Stopwatch chronometer = new Stopwatch();
- chronometer.Start();
- for (int i = 0; i < arr.Length; i++)// changing index of arr
- {
- if (i+k-1 < arr.Length) // Stop before going out of arr boundry
- {
- if (i==0) //Calculating the first sequence k
- {
- for (int j = 0; j < k; j++)
- {
- firstSum = firstSum + arr[i + j];
- lastSum = firstSum;
- }
- }
- else //Calculating the others sequence
- {
- lastSum = (lastSum - arr[i - 1]) + arr[i + k - 1];
- }
- }
- if (lastSum > biggestSum) //Putting the biggest sum in variable
- {
- biggestSum = lastSum;
- }
- }
- Console.WriteLine("The biggest sum is {0}",biggestSum);
- chronometer.Stop();
- Console.WriteLine(chronometer.Elapsed);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement