Advertisement
Klaxon

[C# Arrays] Maximal Sum Array

Jul 15th, 2013
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.15 KB | None | 0 0
  1. // 6. 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. using System;
  4.  
  5. class MaximalSumArray
  6. {
  7.     static void Main()
  8.     {
  9.         Console.Write("Enter wanted array size: ");
  10.         int n = int.Parse(Console.ReadLine());
  11.  
  12.         Console.Write("Enter number of elements to count: ");
  13.         int k = int.Parse(Console.ReadLine());
  14.  
  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.         int sum = 0;
  23.         int maxSum = int.MinValue;
  24.  
  25.         // loops for calculating sums of numbers to K
  26.         for (int i = 0; i <= n - k; i++)
  27.         {
  28.             for (int j = i; j < i + k; j++)
  29.             {
  30.                 sum += array[j];
  31.             }
  32.             // store max sum found
  33.             if (sum > maxSum)
  34.             {
  35.                 maxSum = sum;
  36.             }
  37.             sum = 0;
  38.         }
  39.         // print the result
  40.         Console.WriteLine("The maximal sum in the array with K elements is: {0}", maxSum);
  41.     }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement