Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* 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.*/
- using System;
- class ElementsMaxSum
- {
- static void Main()
- {
- Console.Write("Write number for N: ");
- int N = int.Parse(Console.ReadLine());
- Console.Write("Write number for K: ");
- int K = int.Parse(Console.ReadLine());
- Console.WriteLine("\nWrite the elements of the array: ");
- int[] array = new int[N];
- for (int i = 0; i < N; i++)
- {
- Console.Write("Element {0}: ", i);
- array[i] = int.Parse(Console.ReadLine());
- }
- int sum = 0;
- int maxSum = 0;
- int index = 0;
- for (int i = 0; i <= N - K; i++)
- {
- sum = array[i];
- for (int p = i + 1; p < i + K; p++)
- {
- sum += array[p];
- }
- if (sum > maxSum)
- {
- maxSum = sum;
- index = i;
- }
- }
- Console.Write("Maximum sum of K elements are: ");
- for (int i = index; i < index + K; i++)
- {
- Console.Write("{0} ", array[i]);
- }
- Console.WriteLine("\n");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement