Triplets with Sum between given range - The Coding Shala

Home >> Interview Questions >> Triplets with sum between given range

Triplets with Sum between given range Java Solution

Given an array of real numbers greater than zero in the form of strings.

Find if there exists a triplet (a,b,c) such that 1 < a+b+c < 2 . 

Return 1 for true or 0 for false.
Triplets with Sum between given range - The Coding Shala

Example:
Given [0.6, 0.7, 0.8, 1.2, 0.4] ,
You should return 1
as
0.6+0.7+0.4=1.7
1<1.7<2
Hence, the output is 1.

Triplets with Sum between given range Java Solution

Here an array will be given, we need to find three values whose sum will be in the given range. We can solve this using brute force using three loops but that will give time limit error. 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
public class Solution {
    public int solve(ArrayList<String> A) {
        if(A.size() < 3) return 0;

        double a = Double.parseDouble(A.get(0)); 
        double b = Double.parseDouble(A.get(1)); 
        double c = Double.parseDouble(A.get(2)); 

        for(int i = 3; i < A.size(); i++){
            if((a+b+c) > 1 && (a+b+c) < 2){
                return 1;
            }

            double n = Double.parseDouble(A.get(i));
            
           if((a+b+c) >= 2){
                if(a > b && a > c){
                    a = n;
                } else if( b > c){
                    b = n;
                } else{
                    c = n;
                }
            } 
            else{
                if(a < b && a < c){
                    a = n;
                } else if( b < c){
                    b = n;
                } else{
                    c = n;
                }
            }
        }
        
        if((a+b+c) > 1 && (a+b+c) < 2){
            return 1;
        }
       
        return 0;

    }
}



Other Posts You May Like
Please leave a comment below if you like this post or found some error, it will help me to improve my content.

Comments

Popular Posts from this Blog

Java Method Overloading - The Coding Shala

Java Program to Convert Decimal to Binary - The Coding Shala

Java Program to Find GCD or HCF of Two Numbers - The Coding Shala

Spiral Order Matrix II - The Coding Shala

LeetCode - Crawler Log Folder Solution - The Coding Shala