e.g. i/p: if "AB" and "CD" are two strings
o/p:
ABCD
ACBD
ACDB
ACBD
CABD
CDAB
o/p:
ABCD
ACBD
ACDB
ACBD
CABD
CDAB
#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