Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- class kElementsMaxSum
- {
- static void Main()
- {
- int sizeOfArray ;
- int kElements;
- do
- {
- Console.WriteLine("Please enter the N number of elements in your array:");
- sizeOfArray = int.Parse(Console.ReadLine());
- Console.WriteLine("Please enter the K number of elements \n,to search their max sum:");
- kElements = int.Parse(Console.ReadLine());
- }
- while (kElements > sizeOfArray || kElements <= 0 || sizeOfArray <= 0);
- int[] Array = new int[sizeOfArray];
- int currentSum = 0;
- int maxSum = int.MinValue;
- int currentLen = 0;
- int lastPositionMaxSumElement=0;
- for (int i = 0; i < sizeOfArray; i++)
- {
- Console.WriteLine("Please enter the elements for the array:");
- Array[i] = int.Parse(Console.ReadLine());
- currentSum += Array[i];
- currentLen++;
- if (kElements==currentLen)
- {
- if (currentSum > maxSum)
- {
- maxSum = currentSum;
- lastPositionMaxSumElement = i;
- }
- currentLen = kElements-1;
- currentSum = currentSum-Array[i-kElements+1] ;
- }
- }
- Console.WriteLine("The max sum of {0} elements is:{1}", kElements, maxSum);
- Console.Write("The elements are: {");
- for (int i = lastPositionMaxSumElement - kElements + 1; i <= lastPositionMaxSumElement; i++)
- {
- if (i == lastPositionMaxSumElement)
- {
- Console.WriteLine(Array[i] + "}");
- }
- else
- {
- Console.Write(Array[i] + ", ");
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement