HackerRank 'Two Arrays' Solution

by Srikant Padala on March 20, 2016, 3:44 am


Explanation


The key idea is to sort one array by ascending order and the other by descending order and check if the sum is greater than K for all indices.
Two Arrays Problem Statement

Video

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
 
int main() {
    int T,N, K;
    bool flag;
    cin >> T;
    while(T--) {
        cin >> N >> K;
        vector<int> A(N), B(N);
        for(int i=0; i < N; i++) {
            cin >> A[i];
        }
        for(int i=0; i < N; i++) {
            cin >> B[i];
        }
        sort(A.begin(), A.end());
        sort(B.begin(), B.end(), greater<int>());
        flag = true;
         
        for(int i=0; i < N; i++) {
            if(A[i] + B[i] < K) {
                flag = false;
                break;
            }
        }
        if(flag) cout << "YES" << endl;
        else cout << "NO" << endl;
    }
    return 0;
}

Coming Soon.