GeeksforGeeks » Algorithms
Max sum pairs
(3 posts)-
Max Sum pair
Given two sorted postive integer arrays A(n) and B(n) (W.L.O.G, let's say they are decreasingly sorted),we define a set S = {(a,b) | a \in Aand b \in B}.
Obviously there are n^2 elements in S. The value of such
a pair is defined as Val(a,b) = a + b. Now we want to get the n pairs from S with largest values. The tricky part is that we need an O(n) algorithm.This question is not my inovation. I have copied it here from other forum. COZ it worth discussing it
-
Call a function with passing Both the array and n and fun will return an another array -----------------------------in main-------------------- if(A[n]>B[n]) C=fun(A,B,n); else C=fun(B,A,n); -----------------------end of main------------------------- int fun(int L, int B, int n) { int i=0,j=n-1;k=n-1; while(i<n) // This loop will run less n times say x times { while(L[k--]>=S[j]) // This loop will run less n times say y times { C[i++]=L[k+1]+S[j]; }// end of inner while j--;k=n-1; }// end of while return (C); }// end of fun ------------------------------------------------------- no off loop = x+y = n so it is O(n) I am writing only algo, suggest if its need -
ISM:
your solution has a while loop nested in another while loop, so obviously that is n^2 solution worst case, not (n)
Reply
You must log in to post.