Advertisement
d_brezoev

Untitled

Dec 12th, 2013
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.64 KB | None | 0 0
  1. /*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.
  2. */
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Text;
  6. using System.Diagnostics;
  7. namespace TryHere
  8. {
  9.     class TryHere
  10.     {
  11.         static void Main(string[] args)
  12.         {
  13.             Stopwatch st = new Stopwatch();
  14.             st.Start();
  15.             //int n = 10;
  16.             int k = 3;            
  17.             int[] arr = new int[] { 3,6,1,8,-1,8,11,5,10,-12,100,1,14,65,77,-1,5,23,43,12};
  18.             Queue<int> q = new Queue<int>();
  19.             StringBuilder sb = new StringBuilder();
  20.             string result = string.Empty;          
  21.             int maxSum = int.MinValue;
  22.             for (int i = 0; i < arr.Length; i++)
  23.             {
  24.                 q.Enqueue(arr[i]);                
  25.                 if (q.Count==k)
  26.                 {
  27.                     int sum = 0;
  28.                     //sum all integers in queue
  29.                     foreach (var item in q)
  30.                     {
  31.                         sum += item;
  32.                         sb.Append(item + " ");
  33.                     }
  34.                     if (sum > maxSum)
  35.                     {
  36.                         maxSum = sum;
  37.                         result = sb.ToString();
  38.                     }
  39.                     sb.Clear();
  40.                     q.Dequeue();                    
  41.                 }
  42.             }
  43.             Console.WriteLine(result);
  44.             st.Stop();
  45.             TimeSpan ts = st.Elapsed;
  46.             Console.WriteLine(ts);            
  47.         }
  48.     }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement