In this HackerRank Permuting Two Arrays problem solution there are two n element arrays of integers A and B. we need to permute them into some A’ and B’ such that the relation A'[i] + B'[i] >= k holds for all I where 0 <= I < n. and there are q queries consisting of A, B, and k. for each query return YES if some permutation A’.B’ satisfying the relation exists. otherwise, return NO.
Problem solution in Python.
#!/usr/bin/env python3 def rl(T=str): return list(map(T,input().split())) T, = rl(int) for _ in range((T)): N,K = rl(int) A = rl(int) B = rl(int) A.sort() B.sort(reverse=True) bad = len([a+b for a,b in zip(A,B) if a+b<K ])>0 print("NO" if bad else "YES")
Problem solution in Java.
import java.util.*; public class Solution { public static void main(String[] args) { Scanner in = new Scanner(System.in); int t = in.nextInt(); while (t-- > 0) { int n = in.nextInt(); int k = in.nextInt(); int[] a = new int[n]; int[] b = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } for (int i = 0; i < n; i++) { b[i] = in.nextInt(); } Arrays.sort(a); Arrays.sort(b); solve(a, b, k); } } private static void solve(int[] a, int[] b, int k) { for(int i=0, j=a.length-1; i<a.length; i++, j--){ if(a[i]+b[j] < k) { System.out.println("NO"); return; } } System.out.println("YES"); } }
Problem solution in C++.
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <stdlib.h> using namespace std; int compare1(const void * a, const void * b) { return ( *(int*)b - *(int*)a ); } int compare2(const void * a, const void * b) { return ( *(int*)a - *(int*)b ); } int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ long t; long n, k; long a[1000], b[1000]; cin>>t; for(int i=0; i < t; i++) { cin>>n>>k; for(int j=0; j<n; j++) { cin>>a[j]; } qsort (a, n, sizeof(long), compare1); for(int j=0; j<n; j++) cin>>b[j]; qsort (b, n, sizeof(long), compare2); bool flag=true; for(int i=0; i<n; i++) if(a[i]+b[i]<k) { flag = false; break; } if(flag) cout<<"YESn"; else cout<<"NOn"; } return 0; }
Problem solution in C.
#include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> int compare (const void * a, const void * b) { return ( *(int*)a - *(int*)b ); } int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ int T; int dummy; dummy=scanf("%d",&T); int N; int K; int i; for(i=0; i<T; i++) { dummy=scanf("%d",&N); int A[N]; int B[N]; dummy=scanf("%d",&K); int j; for(j=0; j<N; j++) { dummy=scanf("%d",A+j); } for(j=0; j<N; j++) { dummy=scanf("%d",B+j); } /* input fetched */ //sorting arrays... qsort (A, N, sizeof(int), compare); qsort (B, N, sizeof(int), compare); int k; int isPossible = 1; for (k=0; k<N; k++) { if ((isPossible == 1) && (A[k]+B[N-1-k] < K)) isPossible = 0; } if (isPossible == 1) printf("YESn"); else printf("NOn"); } return 0; }