Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* We are given n numbers, e.g. {3, 7, 2, 8, 1, 4, 6, 9}. We split them into triples:
- * sequences of 3 consecutive numbers (except the last sequence that could have 1 or 2 numbers).
- * In our example, the numbers are split into these triples: the first three numbers {3, 7, 2};
- * the second three numbers {8, 1, 4}; the last two numbers {6, 9}. Write a program that enters n numbers
- * and finds the triple with biggest sum of numbers. In our example this is the last triple: {6, 9}.
- * In case there are several triples with the same biggest sum, print the leftmost of them. */
- using System;
- public class BiggestTriple
- {
- public static void Main()
- {
- string input = Console.ReadLine();
- // Create array of strings, splitting the input by space (' ').
- // Elements of the array might be strings like "5" or "-5".
- string[] elements = input.Split(' ');
- // Initialize maximal triple with three empty strings ("").
- string[] maxTriple = new string[3];
- // Initialize maximal sum to the minimal value of the Int32 type.
- int maxSum = int.MinValue;
- // Initialize index to iterate through the array of elements.
- int index = 0;
- // Start to iterate through the elements of the array of elements.
- while (index < elements.Length)
- {
- int currentSum = 0;
- // Initialize current triple with three empty strings ("").
- string[] currentTriple = new string[3];
- for (int i = index; i < index + 3; i++)
- {
- // If i is valid index in the array of elements, assign it to the current triple.
- if (i < elements.Length)
- {
- // Assign at index 0, 1 or 2 in the current triple.
- currentTriple[i % 3] = elements[i];
- // Collect the sum of the current triple.
- currentSum += int.Parse(currentTriple[i % 3]);
- }
- // Else the element of the current triple is left empty string ("").
- }
- // Assign current triple to the maximal triple, if it's sum is greater than
- // the sum of the maximal triple, found so far.
- // As the comparison is '>', we always keep the leftmost triple
- // in case of the triples with same sum. */
- if (currentSum > maxSum)
- {
- maxSum = currentSum;
- // Get the values of the current triple as maximal triple.
- for (int i = 0; i < 3; i++)
- {
- maxTriple[i] = currentTriple[i];
- }
- }
- // Advance to the start index of the next triple.
- index += 3;
- }
- // Print the contents of the maximal triple array,
- // converting it to string, containing all elements of the array, separated by space.
- Console.WriteLine(string.Join(" ", maxTriple));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement