This week only. Pastebin PRO Accounts Christmas Special! Don't miss out!Want more features on Pastebin? Sign Up, it's FREE!
Guest

Find Elements That Have Maximal Sum

By: ScorpS on Jan 6th, 2013  |  syntax: C#  |  size: 0.85 KB  |  views: 575  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  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. }
clone this paste RAW Paste Data