Saturday, July 2, 2022

Insert Operator (Recursion)

 Insert Operator (Recursion)

Problem Statement
You are given a sequence of numbers of size N. You have to find if there is a way to insert + or - operator in between the numbers so that the result equals K.

import java.io.*; // for handling input/output
import java.util.*; // contains Collections framework

// don't change the name of this class
// you can add inner classes if needed
class Main {
    public static int rec(long []arr,long sum,int i){
         System.out.println("sum = "+sum);
        if(i==arr.length){
            if(sum==0){
                return 0;
            }else{
                return 1;
            }
        }
        return rec(arr,sum-arr[i],i+1)*rec(arr,sum+arr[i],i+1);
    }
    public static void main (String[] args) {
                      // Your code here
                      Scanner sc = new Scanner(System.in);
                      int n = sc.nextInt();
                      long target = sc.nextLong();
                      long []arr = new long[n];
                      for(int i=0;i<n;i++){
                          arr[i] = sc.nextLong();
                      }
                      int sum=(rec(arr,target,0));
                      System.out.println("sum = "+sum);
                      if(sum==0){
                          System.out.println("YES");
                      }else
                      {
                          System.out.println("NO");
                      }
    }
}

No comments:

Post a Comment

ads vert

Basic HTML Tables - Layout, HTML Tables, Attributes, Aside, Footer, Tr tag, Td tag, Th tag, Tbody

  Basic HTML Tables - Layout, HTML Tables, Attributes, Aside, Footer, Tr tag, Td tag, Th tag, Tbody < table >      < thead >    ...