Given 2 Sorted arrays A, B in decreasing order of size m and n respectively and a number k, such that 1 <= k <= m*n. You need to find the kth largest sum(a+b) possible where a in A, and b in B.
Algorithm:
Take 0th index value from 1st array & 1st index value from 2nd array store it in S1
Now 0th index value from 2nd array & 1st index value from 1st array , store in S2
Also stores starting & ending index of each array -take care-off
iniatlize maxsum variable to a[0]+b[0]
Keep checking until we found kth sum from array a & b where a is from 1st & b is from
if s1>s2 then increment array b lastindex untill its equal to length of this array & update maxsum=s1
else then increment array a lastindex until its equal to length of this array
maxsum=s2;
Finally Return maxsum;
2nd array.
maxsum=s2;
Finally Return maxsum;
#include<stdio.h> int k_sum(int A[],int B[],int m,int n,int k){ int indexA = 1; int indexB = 1; int i,s1,s2,sA=0,sB=0; int maxsum = A[0] + B[0]; for(i=0;i<k-1;i++) { s1 = A[sA] + B[indexB]; s2 = A[indexA] + B[sB]; if(s1 >= s2){ if(indexB == n-1){ indexB = sB + 1; ++sA; } else{ ++indexB; } maxsum = s1; } else{ if(indexA == m-1){ indexA = sA + 1; ++sB; } else{ ++indexA; } maxsum = s2; } } return maxsum; } int main(){ int A[5]= {10,9,6,4,3}; int B[6] = {15,13,12,10,78,5}; int k=10; printf("%d \n",k_sum(A,B,5,6,10)); return 0; }
Time Complexity O(K) K=M*N M,N are length of length of array s1,s2
Space Complexity O(1)
https://ideone.com/2IxZX
Run Here https://ideone.com/5Zy8B