Find largest d in array such that a + b + c = d
Last Updated :
07 Mar, 2023
Given a set S (all distinct elements) of integers, find the largest d such that a + b + c = d
where a, b, c, and d are distinct elements of S.
Constraints:
1 ? number of elements in the set ? 1000
INT_MIN ? each element in the set ? INT_MAX
Examples :
Input : S[] = {2, 3, 5, 7, 12}
Output : 12
Explanation: 12 is the largest d which can be represented as 12 = 2 + 3 + 7
Input : S[] = {2, 16, 64, 256, 1024}
Output : No solution
Method 1(Brute Force): We can solve this problem using simple brute force approach which is not very efficient as |S| can be as large as 1000. We'll sort the set of elements and start by finding the largest d by equating it with the sum of all possible combinations of a, b and c.
Steps to solve the problem:
- Sort the input array S in ascending order.
- Iterate the input array S in reverse order. For each S[i]:
- Iterate over all unique combinations of three elements j, k, l from the remaining elements in S, such that j < k < l and i != j != k !=
- if S[j] + S[k] + S[l] == S[i], return S[i] as the largest possible value for d.
- If no such combination is found, return INT_MIN.
Below is the implementation of above idea :
C++
// CPP Program to find the largest d
// such that d = a + b + c
#include <bits/stdc++.h>
using namespace std;
int findLargestd(int S[], int n)
{
bool found = false;
// sort the array in
// ascending order
sort(S, S + n);
// iterating from backwards to
// find the required largest d
for (int i = n - 1; i >= 0; i--)
{
for (int j = 0; j < n; j++)
{
// since all four a, b, c,
// d should be distinct
if (i == j)
continue;
for (int k = j + 1; k < n; k++)
{
if (i == k)
continue;
for (int l = k + 1; l < n; l++)
{
if (i == l)
continue;
// if the current combination
// of j, k, l in the set is
// equal to S[i] return this
// value as this would be the
// largest d since we are
// iterating in descending order
if (S[i] == S[j] + S[k] + S[l])
{
found = true;
return S[i];
}
}
}
}
}
if (found == false)
return INT_MIN;
}
// Driver Code
int main()
{
// Set of distinct Integers
int S[] = { 2, 3, 5, 7, 12 };
int n = sizeof(S) / sizeof(S[0]);
int ans = findLargestd(S, n);
if (ans == INT_MIN)
cout << "No Solution" << endl;
else
cout << "Largest d such that a + b + "
<< "c = d is " << ans << endl;
return 0;
}
Java
// Java Program to find the largest
// such that d = a + b + c
import java.io.*;
import java.util.Arrays;
class GFG
{
// function to find largest d
static int findLargestd(int []S, int n)
{
boolean found = false;
// sort the array in
// ascending order
Arrays.sort(S);
// iterating from backwards to
// find the required largest d
for (int i = n - 1; i >= 0; i--)
{
for (int j = 0; j < n; j++)
{
// since all four a, b, c,
// d should be distinct
if (i == j)
continue;
for (int k = j + 1; k < n; k++)
{
if (i == k)
continue;
for (int l = k + 1; l < n; l++)
{
if (i == l)
continue;
// if the current combination
// of j, k, l in the set is
// equal to S[i] return this
// value as this would be the
// largest d since we are
// iterating in descending order
if (S[i] == S[j] + S[k] + S[l])
{
found = true;
return S[i];
}
}
}
}
}
if (found == false)
return Integer.MAX_VALUE;
return -1;
}
// Driver Code
public static void main(String []args)
{
// Set of distinct Integers
int []S = new int[]{ 2, 3, 5, 7, 12 };
int n = S.length;
int ans = findLargestd(S, n);
if (ans == Integer.MAX_VALUE)
System.out.println("No Solution");
else
System.out.println("Largest d such that " +
"a + " + "b + c = d is " +
ans );
}
}
// This code is contributed by Sam007
Python3
# Python Program to find the largest
# d such that d = a + b + c
def findLargestd(S, n) :
found = False
# sort the array in ascending order
S.sort()
# iterating from backwards to
# find the required largest d
for i in range(n-1, -1, -1) :
for j in range(0, n) :
# since all four a, b, c,
# d should be distinct
if (i == j) :
continue
for k in range(j + 1, n) :
if (i == k) :
continue
for l in range(k+1, n) :
if (i == l) :
continue
# if the current combination
# of j, k, l in the set is
# equal to S[i] return this
# value as this would be the
# largest d since we are
# iterating in descending order
if (S[i] == S[j] + S[k] + S[l]) :
found = True
return S[i]
if (found == False) :
return -1
# Driver Code
# Set of distinct Integers
S = [ 2, 3, 5, 7, 12 ]
n = len(S)
ans = findLargestd(S, n)
if (ans == -1) :
print ("No Solution")
else :
print ("Largest d such that a + b +" ,
"c = d is" ,ans)
# This code is contributed by Manish Shaw
# (manishshaw1)
C#
// C# Program to find the largest
// such that d = a + b + c
using System;
class GFG
{
// function to find largest d
static int findLargestd(int []S,
int n)
{
bool found = false;
// sort the array
// in ascending order
Array.Sort(S);
// iterating from backwards to
// find the required largest d
for (int i = n - 1; i >= 0; i--)
{
for (int j = 0; j < n; j++)
{
// since all four a, b, c,
// d should be distinct
if (i == j)
continue;
for (int k = j + 1; k < n; k++)
{
if (i == k)
continue;
for (int l = k + 1; l < n; l++)
{
if (i == l)
continue;
// if the current combination
// of j, k, l in the set is
// equal to S[i] return this
// value as this would be the
// largest dsince we are
// iterating in descending order
if (S[i] == S[j] + S[k] + S[l])
{
found = true;
return S[i];
}
}
}
}
}
if (found == false)
return int.MaxValue;
return -1;
}
// Driver Code
public static void Main()
{
// Set of distinct Integers
int []S = new int[]{ 2, 3, 5, 7, 12 };
int n = S.Length;
int ans = findLargestd(S, n);
if (ans == int.MaxValue)
Console.WriteLine( "No Solution");
else
Console.Write("Largest d such that a + " +
"b + c = d is " + ans );
}
}
// This code is contributed by Sam007
PHP
<?php
// PHP Program to find the largest
// d such that d = a + b + c
function findLargestd( $S, $n)
{
$found = false;
// sort the array in
// ascending order
sort($S);
// iterating from backwards to
// find the required largest d
for ( $i = $n - 1; $i >= 0; $i--)
{
for ( $j = 0; $j < $n; $j++)
{
// since all four a, b, c,
// d should be distinct
if ($i == $j)
continue;
for ( $k = $j + 1; $k < $n; $k++)
{
if ($i == $k)
continue;
for ( $l = $k + 1; $l < $n; $l++)
{
if ($i == $l)
continue;
// if the current combination
// of j, k, l in the set is
// equal to S[i] return this
// value as this would be the
// largest d since we are
// iterating in descending order
if ($S[$i] == $S[$j] + $S[$k] + $S[$l])
{
$found = true;
return $S[$i];
}
}
}
}
}
if ($found == false)
return PHP_INT_MIN;
}
// Driver Code
// Set of distinct Integers
$S = array( 2, 3, 5, 7, 12 );
$n = count($S);
$ans = findLargestd($S, $n);
if ($ans == PHP_INT_MIN)
echo "No Solution" ;
else
echo "Largest d such that a + b + " ,
"c = d is " , $ans ;
// This code is contributed by anuj_67.
?>
JavaScript
<script>
// Javascript Program to find the largest
// such that d = a + b + c
// function to find largest d
function findLargestd(S, n)
{
let found = false;
// sort the array
// in ascending order
S.sort();
// iterating from backwards to
// find the required largest d
for (let i = n - 1; i >= 0; i--)
{
for (let j = 0; j < n; j++)
{
// since all four a, b, c,
// d should be distinct
if (i == j)
continue;
for (let k = j + 1; k < n; k++)
{
if (i == k)
continue;
for (let l = k + 1; l < n; l++)
{
if (i == l)
continue;
// if the current combination
// of j, k, l in the set is
// equal to S[i] return this
// value as this would be the
// largest dsince we are
// iterating in descending order
if (S[i] == S[j] + S[k] + S[l])
{
found = true;
return S[i];
}
}
}
}
}
if (found == false)
return Number.MAX_VALUE;
return -1;
}
// Set of distinct Integers
let S = [ 2, 3, 5, 7, 12 ];
let n = S.length;
let ans = findLargestd(S, n);
if (ans == Number.MAX_VALUE)
document.write( "No Solution");
else
document.write("Largest d such that a + " +
"b + c = d is " + ans );
</script>
Output : Largest d such that a + b + c = d is 12
This brute force solution has a time complexity of O((size of Set)4).
Method 2(Efficient Approach - Using Hashing): The above problem statement (a + b + c = d) can be restated as finding a, b, c, d such that a + b = d - c. So this problem can be efficiently solved using hashing.
- Store sums of all pairs (a + b) in a hash table
- Traverse through all pairs (c, d) again and search for (d - c) in the hash table.
- If a pair is found with the required sum, then make sure that all elements are distinct array elements and an element is not considered more than once.
Below is the implementation of above approach.
C++
// A hashing based CPP program to find largest d
// such that a + b + c = d.
#include <bits/stdc++.h>
using namespace std;
// The function finds four elements with given sum X
int findFourElements(int arr[], int n)
{
// Store sums (a+b) of all pairs (a,b) in a
// hash table
unordered_map<int, pair<int, int> > mp;
for (int i = 0; i < n - 1; i++)
for (int j = i + 1; j < n; j++)
mp[arr[i] + arr[j]] = { i, j };
// Traverse through all pairs and find (d -c)
// is present in hash table
int d = INT_MIN;
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
int abs_diff = abs(arr[i] - arr[j]);
// If d - c is present in hash table,
if (mp.find(abs_diff) != mp.end()) {
// Making sure that all elements are
// distinct array elements and an element
// is not considered more than once.
pair<int, int> p = mp[abs_diff];
if (p.first != i && p.first != j &&
p.second != i && p.second != j)
d = max(d, max(arr[i], arr[j]));
}
}
}
return d;
}
// Driver program to test above function
int main()
{
int arr[] = { 2, 3, 5, 7, 12 };
int n = sizeof(arr) / sizeof(arr[0]);
int res = findFourElements(arr, n);
if (res == INT_MIN)
cout << "No Solution.";
else
cout << res;
return 0;
}
Java
// A hashing based Java program to find largest d
// such that a + b + c = d.
import java.util.HashMap;
import java.lang.Math;
// To store and retrieve indices pair i & j
class Indexes
{
int i, j;
Indexes(int i, int j)
{
this.i = i;
this.j = j;
}
int getI()
{
return i;
}
int getJ()
{
return j;
}
}
class GFG {
// The function finds four elements with given sum X
static int findFourElements(int[] arr, int n)
{
HashMap<Integer, Indexes> map = new HashMap<>();
// Store sums (a+b) of all pairs (a,b) in a
// hash table
for (int i = 0; i < n - 1; i++)
{
for (int j = i + 1; j < n; j++)
{
map.put(arr[i] + arr[j], new Indexes(i, j));
}
}
int d = Integer.MIN_VALUE;
// Traverse through all pairs and find (d -c)
// is present in hash table
for (int i = 0; i < n - 1; i++)
{
for (int j = i + 1; j < n; j++)
{
int abs_diff = Math.abs(arr[i] - arr[j]);
// If d - c is present in hash table,
if (map.containsKey(abs_diff))
{
Indexes indexes = map.get(abs_diff);
// Making sure that all elements are
// distinct array elements and an element
// is not considered more than once.
if (indexes.getI() != i && indexes.getI() != j &&
indexes.getJ() != i && indexes.getJ() != j)
{
d = Math.max(d, Math.max(arr[i], arr[j]));
}
}
}
}
return d;
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 2, 3, 5, 7, 12 };
int n = arr.length;
int res = findFourElements(arr, n);
if (res == Integer.MIN_VALUE)
System.out.println("No Solution");
else
System.out.println(res);
}
}
// This code is contributed by Vivekkumar Singh
Python3
# A hashing based Python3 program to find
# largest d, such that a + b + c = d.
# The function finds four elements
# with given sum X
def findFourElements(arr, n):
# Store sums (a+b) of all pairs (a,b) in a
# hash table
mp = dict()
for i in range(n - 1):
for j in range(i + 1, n):
mp[arr[i] + arr[j]] =(i, j)
# Traverse through all pairs and find (d -c)
# is present in hash table
d = -10**9
for i in range(n - 1):
for j in range(i + 1, n):
abs_diff = abs(arr[i] - arr[j])
# If d - c is present in hash table,
if abs_diff in mp.keys():
# Making sure that all elements are
# distinct array elements and an element
# is not considered more than once.
p = mp[abs_diff]
if (p[0] != i and p[0] != j and
p[1] != i and p[1] != j):
d = max(d, max(arr[i], arr[j]))
return d
# Driver Code
arr = [2, 3, 5, 7, 12]
n = len(arr)
res = findFourElements(arr, n)
if (res == -10**9):
print("No Solution.")
else:
print(res)
# This code is contributed by Mohit Kumar
C#
// A hashing based C# program to find
// largest d such that a + b + c = d.
using System;
using System.Collections.Generic;
// To store and retrieve
// indices pair i & j
public class Indexes
{
int i, j;
public Indexes(int i, int j)
{
this.i = i;
this.j = j;
}
public int getI()
{
return i;
}
public int getJ()
{
return j;
}
}
public class GFG
{
// The function finds four elements
// with given sum X
static int findFourElements(int[] arr, int n)
{
Dictionary<int, Indexes> map =
new Dictionary<int, Indexes>();
// Store sums (a+b) of all pairs
// (a,b) in a hash table
for (int i = 0; i < n - 1; i++)
{
for (int j = i + 1; j < n; j++)
{
map.Add(arr[i] + arr[j],
new Indexes(i, j));
}
}
int d = int.MinValue;
// Traverse through all pairs and
// find (d -c) is present in hash table
for (int i = 0; i < n - 1; i++)
{
for (int j = i + 1; j < n; j++)
{
int abs_diff = Math.Abs(arr[i] - arr[j]);
// If d - c is present in hash table,
if (map.ContainsKey(abs_diff))
{
Indexes indexes = map[abs_diff];
// Making sure that all elements are
// distinct array elements and an element
// is not considered more than once.
if (indexes.getI() != i &&
indexes.getI() != j &&
indexes.getJ() != i &&
indexes.getJ() != j)
{
d = Math.Max(d, Math.Max(arr[i],
arr[j]));
}
}
}
}
return d;
}
// Driver code
public static void Main(String[] args)
{
int []arr = { 2, 3, 5, 7, 12 };
int n = arr.Length;
int res = findFourElements(arr, n);
if (res == int.MinValue)
Console.WriteLine("No Solution");
else
Console.WriteLine(res);
}
}
// This code is contributed by 29AjayKumar
JavaScript
<script>
// A hashing based Javascript program to find largest d
// such that a + b + c = d.
// To store and retrieve indices pair i & j
class Indexes
{
constructor(i,j)
{
this.i = i;
this.j = j;
}
getI()
{
return this.i;
}
getJ()
{
return this.j;
}
}
// The function finds four elements with given sum X
function findFourElements(arr,n)
{
let map = new Map();
// Store sums (a+b) of all pairs (a,b) in a
// hash table
for (let i = 0; i < n - 1; i++)
{
for (let j = i + 1; j < n; j++)
{
map.set(arr[i] + arr[j], new Indexes(i, j));
}
}
let d = Number.MIN_VALUE;
// Traverse through all pairs and find (d -c)
// is present in hash table
for (let i = 0; i < n - 1; i++)
{
for (let j = i + 1; j < n; j++)
{
let abs_diff = Math.abs(arr[i] - arr[j]);
// If d - c is present in hash table,
if (map.has(abs_diff))
{
let indexes = map.get(abs_diff);
// Making sure that all elements are
// distinct array elements and an element
// is not considered more than once.
if (indexes.getI() != i && indexes.getI() != j &&
indexes.getJ() != i && indexes.getJ() != j)
{
d = Math.max(d, Math.max(arr[i], arr[j]));
}
}
}
}
return d;
}
// Driver code
let arr=[ 2, 3, 5, 7, 12];
let n = arr.length;
let res = findFourElements(arr, n);
if (res == Number.MIN_VALUE)
document.write("No Solution");
else
document.write(res);
// This code is contributed by patel2127
</script>
The overall Time Complexity for this efficient approach is O(N2) (where N is the size of the set).
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem