Given a int optimumMemory and int[] array with list of available memories find the pair of indexes of memories whose sum of the values will be equal to the optimumMemory?
If there exists more than one such pair whose sum of values are equal to the optimumMemory then filter out the indexes for the below conditions
condition1: find the pair of indices which has maximumMemory
condition2: If there exists 2 pairs with same maximumMemory then select the pair with lowest index
Example: int optimumMemory = 10MB int[] availableMemories= [6,3,8,1,1,4,9,2,9,7]
The pair of indices whose sum is equal to 10MB ={(0,5),(1,9),(2,7),(3,6),(3,8),(4,6),(4,8)};
applying condition1 to the above list ={(3,6),(3,8),(4,6),(4,8)};
applying condition2 to the above list will result in only one order pair = {(3,6)}
import com.sun.tools.javac.util.Pair;
public class Test(){
public static void main(String[] args){
int optimumMemory = 10;
int[] list = new int[]{6,3,8,1,1,4,9,2,9,7};
Pair<Integer,Integer> result = new Pair<>(Integer.MIN_VALUE,Integer.MIN_VALUE);
//2 pointer approach
for(int i=0;i<list.length;i++){
for(int j=i+1;j<list.length;j++){
//checking if the sum of memory is equal to optimumMemory
if(list[i]+list[j] == optimumMemory){
Pair<Integer,Integer> pair = new Pair<>(i,j);
//this happens only once, when the very first pair that satisfies the condition is found
if(result.fst==Integer.MIN_VALUE && result.snd == Integer.MIN_VALUE)
{
result = pair;
continue;
}
int maximumMemoryInResult = Math.max(list[result.fst],list[result.snd]);
int maximumMemoryInPair = Math.max(list[pair.fst],list[pair.snd]);
//applying **condition1**
if(maximumMemoryInResult < maximumMemoryInPair){
result = pair;
continue;
}//end of condition1
//applying **condition2**
else if(maximumMemoryInResult == maximumMemoryInPair){
int minIndexInResult = Math.min(result.fst,result.snd);
int minIndexInPair = Math.min(pair.fst,pair.snd);
if(minIndexInPair<minIndexInResult){
result = pair;
continue;
}
}//end of condition2
}
}//end of j loop
}// end of i loop
}// end of main method
}
Is there any way to improve the code I posted?