Advertisement
ScorpS

Find Elements That Have Maximal Sum

Jan 6th, 2013
629
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.85 KB | None | 0 0
  1. //  Write a program that reads two integer numbers N and K
  2. //  and an array of N elements from the console. Find in the
  3. //  array those K elements that have maximal sum.
  4.  
  5. using System;
  6.  
  7. class FindElementsThatHaveMaximalSum
  8. {
  9.     static void Main()
  10.     {
  11.         int n = int.Parse(Console.ReadLine());
  12.         int k = int.Parse(Console.ReadLine());
  13.         int[] array = new int[n];
  14.         int sum = 0;
  15.  
  16.         if (k > n)
  17.         {
  18.             Console.WriteLine("N must be bigger than K!");
  19.             return;
  20.         }
  21.  
  22.         for (int index = 0; index < n; index++)
  23.         {
  24.             array[index] = int.Parse(Console.ReadLine());  
  25.         }
  26.  
  27.         Array.Sort(array);
  28.  
  29.         for (int index = n - 1; index >= n - k; index--)
  30.         {
  31.             sum += array[index];
  32.         }
  33.  
  34.         Console.WriteLine(sum);
  35.     }
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement