Interview Question
- 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 April 23, 2014 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
package level1;
- rv April 25, 2014import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
public class prob2 {
public static void main(String[] args) {
int[] Input={-6,2,4,8,5,1,0};//
System.out.println(Arrays.toString(findPair(Input)));
}
public static int[] findPair(int[] a){
YourMap hm = new YourMap();
//Arrays.sort(a);
String s=null;
for(int i=0;i<a.length-2;i++){
for(int j=i+1;j<a.length-1;j++){
if(j!=i) for(int k=0;k<a.length;k++)
if(k!=j&&k!=i) for(int l=0;l<a.length;l++)
if(l!=i && l!=j &l!=k) hm.put(a[i]+a[j]+a[k]-a[l],a[i]+"+"+a[j]+"+"+a[k]+"="+a[l]);
}
}
System.out.println(hm.get((Integer)0).toString());
return a;
}
}
class YourMap extends HashMap<Integer, List<String>> {
public void put(Integer key, String number) {
List<String> current = get(key);
if (current == null) {
current = new ArrayList<String>();
super.put(key, current);
}
current.add(number);
}
}