SHARE
TWEET

06. SomeSums

Teodor92 Jan 6th, 2013 851 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* Write a program that reads two
  2.  * integer numbers N and K and an array
  3.  * of N elements from the console. Find
  4.  * in the array those K elements that have maximal sum.
  5.  */
  6.  
  7. using System;
  8.  
  9. class MaximalSum
  10. {
  11.     static void Main()
  12.     {
  13.         // input
  14.         int n = int.Parse(Console.ReadLine());
  15.         int k = int.Parse(Console.ReadLine());
  16.         int[] myArray = new int[n];
  17.         for (int i = 0; i < myArray.Length; i++)
  18.         {
  19.             myArray[i] = int.Parse(Console.ReadLine());
  20.         }
  21.  
  22.         // testing
  23.         //int[] myArray = { 12, 12, 12, 11, 11, 11, 7, 8, 9 };
  24.         // help values
  25.         string bestSeq = "";
  26.         int sum = 0;
  27.         int bestSum = int.MinValue;
  28.         int arrayLen = myArray.Length;
  29.         for (int i = 0; i < arrayLen; i++)
  30.         {
  31.             string currentSeq = "";
  32.             // out of the array bounds
  33.             if (i + k > arrayLen)
  34.             {
  35.                 break;
  36.             }
  37.             // set check
  38.             for (int j = i; j < i + k; j++)
  39.             {
  40.                 sum = sum + myArray[j];
  41.                 currentSeq = currentSeq + ' ' + myArray[j];
  42.             }
  43.             // best sum check
  44.             if (sum > bestSum)
  45.             {
  46.                 bestSeq = currentSeq;
  47.                 bestSum = sum;
  48.             }
  49.             sum = 0;
  50.         }
  51.         Console.WriteLine(bestSeq);
  52.         Console.WriteLine(bestSum);
  53.     }
  54. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top