SHOW:
|
|
- or go back to the newest paste.
1 | using System; | |
2 | using System.Collections.Generic; | |
3 | using System.Text; | |
4 | ||
5 | - | //Task 7:Write a program that reads two integer numbers N and K and an array of N elements from the console. |
5 | + | //Task 6:Write a program that reads two integer numbers N and K and an array of N elements from the console. |
6 | //Find in the array those K elements that have maximal sum. | |
7 | ||
8 | namespace Task6KLlemMaxSum | |
9 | { | |
10 | class KElemMaxSum | |
11 | { | |
12 | static void Main(string[] args) | |
13 | { | |
14 | int sum = 0; | |
15 | int maxsum = int.MinValue; | |
16 | int index = 0; | |
17 | Console.Write("Enter length of array n:"); | |
18 | int n = int.Parse(Console.ReadLine()); | |
19 | Console.Write("Enter number k (1<k<n):"); | |
20 | int k = int.Parse(Console.ReadLine()); | |
21 | if ((k >= n)||(k<=1)) | |
22 | { | |
23 | Console.WriteLine("k < n and k >1! Incorrect data!"); | |
24 | } | |
25 | int[] array = new int[n]; | |
26 | for (int element = 0; element < n; element++) | |
27 | { | |
28 | Console.Write("Enter array[{0}]=", element); | |
29 | array[element] = int.Parse(Console.ReadLine()); //add elements to array | |
30 | } | |
31 | for (int i = 0; i < n - k + 1; i++) | |
32 | { | |
33 | for (int j = i; j < k + i; j++) | |
34 | { | |
35 | sum = sum + array[j]; | |
36 | ||
37 | } | |
38 | if (sum > maxsum) //check max sum | |
39 | { | |
40 | maxsum = sum; | |
41 | index = i; | |
42 | ||
43 | } | |
44 | sum = 0; | |
45 | ||
46 | } | |
47 | Console.WriteLine(maxsum); //print maximal sum | |
48 | for (int max = index; max < index + k; max++) //print k elements with max. sum | |
49 | { | |
50 | Console.Write(array[max] + " "); | |
51 | } | |
52 | Console.WriteLine(); | |
53 | ||
54 | } | |
55 | } | |
56 | } |