Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Text;
- //Task 7: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.
- namespace Task6KLlemMaxSum
- {
- class KElemMaxSum
- {
- static void Main(string[] args)
- {
- int sum = 0;
- int maxsum = int.MinValue;
- int index = 0;
- Console.Write("Enter length of array n:");
- int n = int.Parse(Console.ReadLine());
- Console.Write("Enter number k (1<k<n):");
- int k = int.Parse(Console.ReadLine());
- if ((k >= n)||(k<=1))
- {
- Console.WriteLine("k < n and k >1! Incorrect data!");
- }
- int[] array = new int[n];
- for (int element = 0; element < n; element++)
- {
- Console.Write("Enter array[{0}]=", element);
- array[element] = int.Parse(Console.ReadLine()); //add elements to array
- }
- for (int i = 0; i < n - k + 1; i++)
- {
- for (int j = i; j < k + i; j++)
- {
- sum = sum + array[j];
- }
- if (sum > maxsum) //check max sum
- {
- maxsum = sum;
- index = i;
- }
- sum = 0;
- }
- Console.WriteLine(maxsum); //print maximal sum
- for (int max = index; max < index + k; max++) //print k elements with max. sum
- {
- Console.Write(array[max] + " ");
- }
- Console.WriteLine();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement