Advertisement
Guest User

Biggest Triple

a guest
Mar 20th, 2015
362
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.98 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. class BiggestTriple
  6. {
  7.     static void Main()
  8.     {
  9.         // read, split and parse input line, store in a list of unrestricted count
  10.         List<int> numbers = Console.ReadLine().Split(' ').Select(int.Parse).ToList();
  11.  
  12.         // declaring variables
  13.         int maxSum = Int32.MinValue; // setting to initial Int32.MinValue is important,
  14.         // as we can get all actual sums below 0, and they should still be higher that the initial maxSum value
  15.         int sum = 0;
  16.  
  17.         // declaring two lists (we prefer list to array so that we can have a temp and final lists of 1-3 elements):
  18.         // temp will be storing every slice of 3 numbers, temporarily, until we calculate their sum and compare it to maxSum
  19.         List<int> temp = new List<int>();
  20.         // final will be storing the slice of maximal sum
  21.         List<int> final = new List<int>();
  22.  
  23.         // keep slicing the intial numbers list and removing the slices from it, while numbers.Count >= 3
  24.         while (numbers.Count >= 3)
  25.         {
  26.             temp = numbers.Take(3).ToList(); // taking the first 3 elements of the numbers list
  27.             numbers.RemoveRange(0, 3); // removing the first 3 elements of the numbers list
  28.  
  29.             sum = temp.Sum(); // summing the temp list
  30.  
  31.             if (sum > maxSum) // comparing with maxSum
  32.             {
  33.                 maxSum = sum;
  34.                 final = temp;
  35.             }
  36.         }
  37.  
  38.         // only in case there are still remaining elements in numbers list
  39.         // we will take the last remaining elements ( 1 or 2), sum them and compare with maxSum
  40.         if (numbers.Count != 0)
  41.         {
  42.             temp = numbers;
  43.             sum = temp.Sum();
  44.  
  45.             if (sum > maxSum)
  46.             {
  47.                 maxSum = sum;
  48.                 final = temp;
  49.             }
  50.         }
  51.  
  52.         // printing the result
  53.         Console.WriteLine(string.Join(" ", final));
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement