Joe Flip
BAN USER
I have a java version for O(n^2) at worst case
public class MaxProductOfThree {
public static void getMaxProduct(int[] array){
ArrayList<ArrayList<Integer>> sequences = new ArrayList<ArrayList<Integer>>();
//find all the possible ascending sequences
for(int i=0;i<array.length;i++){
boolean added = false;
for(int j=0;j<sequences.size();j++){
ArrayList<Integer> seq = sequences.get(j);
if(array[i] > seq.get(seq.size()-1)){
seq.add(array[i]);
added = true;
}
}
//if not added to any sequence, means it's a starting number for a new sequence
if(added == false){
ArrayList<Integer> newSeq = new ArrayList<Integer>();
newSeq.add(array[i]);
sequences.add(newSeq);
}
}
int maxProduct = 0;
int[] result = new int[3];
//go thru the last 3 elements of all the ascending sequences, find the max product
for(int j=0;j<sequences.size();j++){
ArrayList<Integer> seq = sequences.get(j);
int s = seq.size();
if(s >= 3){
int product = seq.get(s-3) * seq.get(s-2) * seq.get(s-1);
if(product > maxProduct){
maxProduct = product;
result[0] = seq.get(s-3);
result[1] = seq.get(s-2);
result[2] = seq.get(s-1);
}
}
}
System.out.println("The result is: "+result[0]+", "+result[1]+", "+result[2]);
}
public static void main(String[] args) {
// int[] array = {6,7,8,1,2,3,9,10};
int[] array = {2,3,8,6,7,9};
getMaxProduct(array);
}
}
public class FindUnique {
public static void find(ArrayList<Integer> A, ArrayList<Integer> B){
int posA = 0;
int posB = 0;
ArrayList<Integer> result = new ArrayList<Integer>();
while(posA < A.size() || posB < B.size()){
//if we've been thru one of the lists
if(posA >= A.size()){
result.add(B.get(posB));
posB++;
continue;
}
else if(posB >= B.size()){
result.add(A.get(posA));
posA++;
continue;
}
//put the smaller one into result list
if(A.get(posA) < B.get(posB)){
result.add(A.get(posA));
posA++;
}
else if(A.get(posA) > B.get(posB)){
result.add(B.get(posB));
posB++;
}
else { //when equal, skip to next in both lists
posA++;
posB++;
}
}
//output result
for(int i=0;i<result.size();i++){
System.out.print(result.get(i)+" ");
}
}
}
@constant have you run your code on computer? Your code will print out the duplicate element. Because when arr1[i] == arr2[j], your code will look at arr1[i+1], and if arr1[i+1] > arr2[j], it will print out arr2[j], which is a duplicate
- Joe Flip April 08, 2013