Advertisement
striking

Untitled

Dec 8th, 2013
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.29 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. Find in the array those K elements that have maximal sum.*/
  2.  
  3.  
  4. using System;
  5. class ElementsMaxSum
  6. {
  7.     static void Main()
  8.     {
  9.         Console.Write("Write number for N: ");
  10.         int N = int.Parse(Console.ReadLine());
  11.         Console.Write("Write number for K: ");
  12.         int K = int.Parse(Console.ReadLine());
  13.         Console.WriteLine("\nWrite the elements of the array: ");
  14.  
  15.         int[] array = new int[N];
  16.         for (int i = 0; i < N; i++)
  17.         {
  18.             Console.Write("Element {0}: ", i);
  19.             array[i] = int.Parse(Console.ReadLine());
  20.         }
  21.  
  22.         int sum = 0;
  23.         int maxSum = 0;
  24.         int index = 0;
  25.  
  26.         for (int i = 0; i <= N - K; i++)
  27.         {
  28.             sum = array[i];
  29.             for (int p = i + 1; p < i + K; p++)
  30.             {
  31.                 sum += array[p];
  32.             }
  33.  
  34.             if (sum > maxSum)
  35.             {
  36.                 maxSum = sum;
  37.                 index = i;
  38.             }
  39.         }
  40.  
  41.         Console.Write("Maximum sum of K elements are: ");
  42.         for (int i = index; i < index + K; i++)
  43.         {
  44.             Console.Write("{0} ", array[i]);
  45.         }
  46.         Console.WriteLine("\n");
  47.     }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement