stkirov

06.MaxSumOfKElements

Jan 10th, 2013
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.18 KB | None | 0 0
  1. //Write a program that reads two integer numbers N and K and an array of N elements from the console.
  2. //Find in the array those K elements that have maximal sum.
  3. //{ 12, 12, 12, 11, 11, 11, 7, 8, 9 };
  4. using System;
  5. using System.Collections.Generic;
  6.  
  7. class MaxSumOfKElements
  8. {
  9.     static void Main()
  10.     {
  11.         Console.Write("Enter the number of elements in the array: ");
  12.         int n = int.Parse(Console.ReadLine());
  13.         int[] array = new int[n];
  14.  
  15.         for (int i = 0; i < n; i++)
  16.         {
  17.             Console.Write("[{0}]=", i);
  18.             array[i] = int.Parse(Console.ReadLine());
  19.         }
  20.  
  21.         Console.Write("Enter K: ");
  22.         int k = int.Parse(Console.ReadLine());
  23.  
  24.         int sum = 0;
  25.         int bestSum = 0;
  26.         int length = 0;
  27.  
  28.         for (int i = 0; i < array.Length; i++)
  29.         {
  30.             sum += array[i];
  31.             length++;
  32.             if (sum>bestSum && length == k)
  33.             {
  34.                 bestSum = sum;
  35.             }
  36.             if (length==k)
  37.             {
  38.                 i = (i+1) - k;
  39.                 length = 0;
  40.                 sum = 0;
  41.             }
  42.         }
  43.         Console.WriteLine(bestSum);
  44.     }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment