Advertisement
soxa

MaximalSumOfArraysElements

Dec 15th, 2013
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.09 KB | None | 0 0
  1. using System;
  2. //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.
  3.  
  4. class SumOfArray
  5. {
  6.     static void Main()
  7.     {
  8.         //Input
  9.  
  10.         int n = int.Parse(Console.ReadLine());
  11.         int k = int.Parse(Console.ReadLine());
  12.         int sum = 0;
  13.         int maxSum = 0;
  14.         int minIndex = 0;
  15.         int[] array = new int[n];
  16.  
  17.         for (int i = 0; i < n; i++)
  18.         {
  19.             array[i] = int.Parse(Console.ReadLine());
  20.         }
  21.  
  22.         //Solution
  23.  
  24.         for (int i = 0; i <= (n - k); i++)
  25.         {
  26.             for (int j = i; j < (i + k); j++)
  27.             {
  28.                 sum += array[j]; // Current sum
  29.             }
  30.             if (sum > maxSum)
  31.             {
  32.                 maxSum = sum;
  33.                 minIndex = i; // Get min index of array
  34.             }
  35.             sum = 0;
  36.         }
  37.  
  38.         //Output
  39.  
  40.         for (int i = minIndex; i < (minIndex + k); i++)
  41.         {
  42.             Console.Write("{0} ",array[i]);
  43.         }
  44.     }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement