Magic array

Problem
Given an array of +ve as well as -ve numbers, find out whether it is possible or not to convert it to 0 by adding/subtracting operations on all the elements.

Examples
arr[]={1,2,3}
1+2-3 = 0
Hence ans = YES

using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    class Program
    {
        public static int flag = 0;
        static void Main(string[] args)
        {
            int[] A = {-1, 2, -1};
            checkSum(A, 0, 0);
            if (flag == 1)
            {
                Console.WriteLine("TRUE");
            }
            else
            {
                Console.WriteLine("FALSE");
            }
        }

        public static void checkSum(int[] A, int sum, int i)
        {
            if (i == A.Length && sum == 0)
            {
                flag = 1;
                return;
            }
            if (flag == 0 && i < A.Length)
            {
                checkSum(A, sum + A[i], i + 1);
            }
            if (flag == 0 && i < A.Length)
            {
                checkSum(A, sum - A[i], i + 1);
            }
        }
    }
}

Output
=======
TRUE
Press any key to continue . . .
Advertisements
This entry was posted in Information Technology. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s