Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- class ArrayNFindKelementsMaxSum
- {
- static void Main()
- {
- //Write a program that reads two integer numbers N and K and an array of N elements from the console. Find in the array those K elements that have maximal sum.
- //Read from the console the size of the matrix and the number of elements whose sum we will be checking
- int numN = int.Parse(Console.ReadLine()),
- numK = int.Parse(Console.ReadLine());
- //Initialize the array and read its elemnts
- int[] myIntArray = new int [numN];
- for (int i = 0; i < numN; i++)
- {
- myIntArray[i] = int.Parse(Console.ReadLine());
- }
- //Check the sums of k elemnts in the array
- int currentSum = 0,
- maxSum = 0;
- for (int j = 0; j <= numN-numK; j++)//The cycle goes till there are only k elemnts left, thus the size of the matrix minus the k elements
- {
- for (int innerIndex = j; innerIndex < j+numK; innerIndex++)//The inner loop checks the subset sums of k elements: it starts with the outer j index and end with the j plus k element index
- {
- currentSum += myIntArray[innerIndex]; //cuurent sum sums the elements of each k numbers
- }
- if (currentSum > maxSum)//Here we check if the current sum is bigger than the maximal previous sum
- {
- maxSum = currentSum;
- }
- currentSum = 0; //Current sum should be made zero so that the next check starts from scratch.
- }
- //Print the result on the console
- Console.WriteLine(maxSum);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement