Advertisement
Guest User

Untitled

a guest
May 11th, 2016
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.57 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. namespace alternating_sum
  6. {
  7.  
  8.     class Program
  9.     {
  10.         private static int[] intervals;
  11.  
  12.         private static int max;
  13.  
  14.         static void Main()
  15.         {
  16.             string[] input = Console.ReadLine().Split(',').ToArray();
  17.             for (int i = 0; i < input.Length; i++)
  18.             {
  19.                 input[i] = input[i].Trim();
  20.             }
  21.             intervals = input.Select(int.Parse).ToArray();
  22.             int startDb = int.Parse(Console.ReadLine());
  23.             max = int.Parse(Console.ReadLine());
  24.  
  25.             HashSet<int> actual = new HashSet<int>();
  26.             actual.Add(startDb);
  27.             HashSet<int> spare = new HashSet<int>();
  28.  
  29.             for (int i = 0; i < intervals.Length; i++)
  30.             {
  31.                 foreach (var db in actual)
  32.                 {
  33.                     int subRes = db - intervals[i];
  34.                     if (subRes >= 0)
  35.                     {
  36.                         spare.Add(subRes);
  37.                     }
  38.  
  39.                     int sumRes = db + intervals[i];
  40.                     if (sumRes <= max)
  41.                     {
  42.                         spare.Add(sumRes);
  43.                     }
  44.                 }
  45.  
  46.                 actual = new HashSet<int>(spare);
  47.                 spare.Clear();
  48.             }
  49.  
  50.             if (!actual.Any())
  51.             {
  52.                 Console.WriteLine("-1");
  53.             }
  54.             else
  55.             {
  56.                 Console.WriteLine(actual.Max());
  57.             }
  58.         }
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement