yourkishor
BAN USER- 0of 0 votes
AnswerGiven an array of non-repeating, non-sorted, positive and negative integers, find 4 numbers in that array which satisfy the following equation: A1 + A2 + A3 = A4
Complete the function to return the value A4. If no such numbers satisfy the given equation, return -1,
In case of multiple possibilities that satisfy the equation, return the largest such value of A4.
Sample Test Case:
Sample Input: {-6,2,4,8}
Sample Output: 4
Explanation: The value 4 can be achieved as follows: 8+2+(-6) = 4
IMPORTANT: You do not need to write full code. Just complete the given function.
- yourkishor in United States/**This class find sequence of elements in an array which satifies a1+a2+a3=a4. * @author Kishor Kumar Padhan * */ public class EquationInArray { public static void main(String[] args) { int[] arr = new int[] {-6,2,4,8}; int[][] arr1 = new int[arr.length*(arr.length-1)][2]; int k=0; for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr.length; j++) { if(i!=j) { arr1[k][0] = arr[i]; arr1[k][1] = arr[j]; k++; } } } int bigMatchedNumber=0; String bigMatchedEquation=""; int m=0; while(m<arr1.length) { for(int n=0;n<arr.length;n++) { if(arr1[m][0]!=arr1[n][1] && arr1[m][1]!=arr1[n][1]) { int total = arr1[m][0]+arr1[m][1]+arr1[n][1]; if(doesNumberExists(total,arr)) { if(total>bigMatchedNumber) { bigMatchedNumber=total; bigMatchedEquation = arr1[m][0]+"+"+arr1[m][1]+"+"+arr1[n][1]+"="+total; } } } } m++; } System.out.println("bigMatchedEquation : " + bigMatchedEquation); } private static boolean doesNumberExists(int total, int[] arr) { boolean matched = false; for (int i = 0; i < arr.length; i++) { if(total == arr[i]) { matched = true; } } return matched; } }
| Report Duplicate | Flag | PURGE
Algorithm