Advertisement
sylviapsh

Find in array N those K elements that have maximal sum

Jan 9th, 2013
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.51 KB | None | 0 0
  1. using System;
  2. class ArrayNFindKelementsMaxSum
  3. {
  4.   static void Main()
  5.   {
  6.     //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.
  7.  
  8.     //Read from the console the size of the matrix and the number of elements whose sum we will be checking
  9.     int numN = int.Parse(Console.ReadLine()),
  10.         numK = int.Parse(Console.ReadLine());
  11.  
  12.     //Initialize the array and read its elemnts
  13.     int[] myIntArray = new int [numN];
  14.  
  15.     for (int i = 0; i < numN; i++)
  16.     {
  17.       myIntArray[i] = int.Parse(Console.ReadLine());
  18.     }
  19.  
  20.     //Check the sums of k elemnts in the array
  21.     int currentSum = 0,
  22.         maxSum = 0;
  23.     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
  24.     {
  25.       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
  26.       {
  27.         currentSum += myIntArray[innerIndex]; //cuurent sum sums the elements of each k numbers
  28.       }
  29.       if (currentSum > maxSum)//Here we check if the current sum is bigger than the maximal previous sum
  30.       {
  31.         maxSum = currentSum;
  32.       }
  33.       currentSum = 0; //Current sum should be made zero so that the next check starts from scratch.
  34.     }
  35.  
  36.     //Print the result on the console
  37.     Console.WriteLine(maxSum);
  38.   }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement