Advertisement
Opteronic

cs arr j08 Subset Of Sum S _SORT ARRAY

Mar 13th, 2018
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.20 KB | None | 0 0
  1. /*
  2. We are given an array of longegers and a number S. Write a program to find
  3. if there exists a subset of the elements of the array that has a sum S.
  4.  */
  5. using System;
  6. public class SubsetOfSumS
  7. {
  8.     public static void Main()
  9.     {
  10.         long n = long.Parse(Console.ReadLine()), c = 0;
  11.         long sum = 0;//long n = 14, c = 0, sum = 0;//
  12.  
  13.         string[] str = Console.ReadLine().Split(' ');
  14.         long[] ar = new long[str.Length];
  15.         for (long i = 0; i < str.Length; i++)
  16.             ar[i] = Convert.ToInt64(str[i]);
  17.         // long[] ar = {2, 1, 2, 4, 3, 0, 9, 6};//8
  18.  
  19.         // Array.Sort(ar);
  20.         for (long i = ar.Length - 1; i >= 0; i--)
  21.         {
  22.             sum = 0;
  23.             for (long j = 0; j < ar.Length; j++)
  24.             {
  25.                 if (i != j)
  26.                 {
  27.                     sum = sum + ar[j];
  28.                     if (sum == n)
  29.                     {
  30.                         Console.WriteLine("yes"); c++; break;
  31.                     }
  32.                     if (sum > n)
  33.                         sum = sum - ar[j];
  34.                 }
  35.             }
  36.             if (c == 1) break;
  37.         }
  38.         if (c == 0)
  39.             Console.WriteLine("no");
  40.     }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement