Check out the Pastebin Gadgets Shop. We have thousands of fun, geeky & affordable gadgets on sale :-)Want more features on Pastebin? Sign Up, it's FREE!
tweet

# Untitled

By: minusa71 on Jan 12th, 2013  |  syntax: None  |  size: 1.76 KB  |  views: 16  |  expires: Never
This paste has a previous version, view the difference. Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
1. using System;
2. using System.Collections.Generic;
3. using System.Text;
4.
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.
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:");
19.             Console.Write("Enter number k (1<k<n):");
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);
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. }
clone this paste RAW Paste Data
Top