Perfect Sums

 Coding Problem Keys 

 Perfect Sums 

 Problem Statement 

A Perfect sum is the sum of two or more elements of an array which is equal to a given number. Your task is to write a function to compute the number of perfect sums existing in an array.

Note: If no such sum exits, return 999. Also, if the input array is not an integer array, then also return 999.

 Input Format 

input1: An integer value representing the length of the integer array.
input2: An integer array of length N.
input3: An integer value representation the number, the perfect sum must be equal to.

 Output Format 

Return the number of perfect sums existing in the array.

 Example 1 

 Input 

input1: 5
input2: {9, 7, 3, 12, 7}
input3: 14

 Output 

output: 1

 Explanation 

Here, the sum of elements 7 + 7 = 14. Hence the number of perfect sums in the given array is 1. Therefore, 1 is returned as the output.

 Example 2 

 Input 

input1: 5
input2: {4, 7, 8, 2, 3}
input3: 12

 Output 

output: 2

 Note: Max Execution Time Limit: 50 millisecs 

 Solution 

 Programming Language: C++ Language 

#include <iostream>
using namespace std;
int PerfectSum(int input1,int input2[], int input3){
    //Check whether each element in input2[] is a integer if not return 999
    int t[input1+1][input3+1];
    for(int i=1;i<=input3;i++)
        t[0][i]=0;
    for(int i=0;i<=input1;i++)
        t[i][0]=1;
    for(int i=1;i<=input1;i++){
        for(int j=1;j<=input3;j++){
            if(input2[i-1]<=j)
                t[i][j] = (t[i-1][j] + t[i-1][j-input2[i-1]]);
            else
                t[i][j] = t[i-1][j];
        }
    }
    return t[input1][input3];
    // Here if no such sum exists return 999
}
int main() {
    int input1,input3;
    int input2[input1];
    cin>>input1;
    for(int i=0;i<input1;i++)
        cin>>input2[i];
    cin>>input3;
    cout<<PerfectSum(input1,input2,input3);
}

// Published By PKJCODERS

 (Note: Incase If the code doesn't Pass the output kindly comment us with your feedback to help us improvise.) 

Comments

Popular Posts

Count Number of Occurrences of a Character

Print Prime Numbers from 2 to N

Cities and Population

K Palindrome Integers

Most Vowels in Row

Sum - Odd Number of Digits

Sum of Numbers - XOR and OR