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 MaxSumKofN
- {
- static void Main()
- {
- Console.Write("Enter the array length: ");
- int length = int.Parse(Console.ReadLine());
- int[] array = new int[length];
- Console.Write("Enter the number of elements for finding the max sum: ");
- int elements = int.Parse(Console.ReadLine());
- int combinations = (int)Math.Pow(2,length);
- long totalSum = 0;
- int[] members = new int[length];
- for (int i = 0; i < length; i++)
- {
- Console.Write("Enter elements[{0}] value: ", i + 1);
- array[i] = int.Parse(Console.ReadLine());
- }
- for (int i = 1; i <= combinations; i++)
- {
- int count1s = 0;
- for (int g = 0; g < length; g++)
- {
- if ((i & (1 << g)) != 0) count1s++;
- }
- if (count1s == elements)
- {
- int sum = 0;
- for (int g = 0; g < length; g++)
- {
- if ((i & (1 << g)) != 0)
- {
- sum += array[g];
- }
- }
- if (sum > totalSum)
- {
- totalSum = sum;
- for (int k = 0; k < length; k++) members[k] = 0;
- for (int g = 0; g < length; g++)
- {
- if ((i & 1 << g) != 0)
- {
- members[g] = 1;
- }
- }
- }
- }
- }
- Console.Write("The {0} elements in the array with MaxSum {1} are: ", elements,totalSum);
- for (int i = 0; i < length; i++)
- {
- if(members[i] == 1) Console.Write("{0} ",array[i]);
- }
- Console.WriteLine();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement