Skip to content
Related Articles

Related Articles

Reduce sum of same-indexed elements of two arrays to less than K by rearranging the second array
  • Last Updated : 28 Jan, 2021

Given two arrays arr1[] and arr2[], both of size N and an integer X, the task is to check if the sum of same-indexed elements of both the arrays at corresponding indices can be made at most K after rearranging the second array. If it is possible then print “Yes” else print “No”.

Examples:

Input: arr1[] = {1, 2, 3}, arr2[] = {1, 1, 2}, X = 4
Output: Yes
Explanation:
Rearranging the array B[] as {1, 2, 1}. Now the sum of corresponding indices are:
A[0] + B[0] = 1 + 1 = 2 ≤ 4
A[1] + B[1] = 2 + 2 = 4 ≤ 4
A[2] + B[2] = 3 + 1 = 4 ≤ 4

Input: arr1[] = {1, 2, 3, 4}, arr2[] = {1, 2, 3, 4},  X = 4
Output: No
Explanation: There is no way that the array B[] can be rearranged such that the condition A[i] + B[i] <= X is satisfied.

Naive Approach: The simplest approach is to generate all possible permutations of the array B[] and if any permutation satisfies the given condition, then print Yes. Otherwise, print No
Time Complexity: O(N!)
Auxiliary Space: O(1)

Efficient Approach: To optimize the above approach, the idea is to use Sorting. Follow the steps below to solve the problem:



Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approch
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if elements
// of B[] can be rearranged
// such that A[i] + B[i] <= X
void rearrange(int A[], int B[],
               int N, int X)
{
    // Checks the given condition
    bool flag = true;
 
    // Sort A[] in ascending order
    sort(A, A + N);
 
    // Sort B[] in descending order
    sort(B, B + N, greater<int>());
 
    // Traverse the arrays A[] and B[]
    for (int i = 0; i < N; i++) {
 
        // If A[i] + B[i] exceeds X
        if (A[i] + B[i] > X) {
 
            // Rearrangement not possible,
            // set flag to false
            flag = false;
            break;
        }
    }
 
    // If flag is true
    if (flag)
        cout << "Yes";
 
    // Otherwise
    else
        cout << "No";
}
 
// Driver Code
int main()
{
    int A[] = { 1, 2, 3 };
    int B[] = { 1, 1, 2 };
    int X = 4;
    int N = sizeof(A) / sizeof(A[0]);
 
    // Function Call
    rearrange(A, B, N, X);
 
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for the above approch
import java.util.*;
class GFG
{
 
  // Function to check if elements
  // of B[] can be rearranged
  // such that A[i] + B[i] <= X
  static void rearrange(int A[], int B[],
                        int N, int X)
  {
 
    // Checks the given condition
    boolean flag = true;
 
    // Sort A[] in ascending order
    Arrays.sort(A);
 
    // Sort B[] in descending order
    Arrays.sort(B);
 
    // Traverse the arrays A[] and B[]
    for (int i = 0; i < N; i++)
    {
 
      // If A[i] + B[i] exceeds X
      if (A[i] + B[N - 1 - i] > X)
      {
 
        // Rearrangement not possible,
        // set flag to false
        flag = false;
        break;
      }
    }
 
    // If flag is true
    if (flag == true)
      System.out.print("Yes");
 
    // Otherwise
    else
      System.out.print("No");
  }
 
  // Driver Code
  public static void main (String[] args)
  {
    int A[] = { 1, 2, 3 };
    int B[] = { 1, 1, 2 };
    int X = 4;
    int N = A.length;
 
    // Function Call
    rearrange(A, B, N, X);
  }
}
 
// This code is contributed by AnkThon

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program for the above approch
 
# Function to check if elements
# of B can be rearranged
# such that A[i] + B[i] <= X
def rearrange(A, B, N, X):
   
    # Checks the given condition
    flag = True
 
    # Sort A in ascending order
    A = sorted(A)
 
    # Sort B in descending order
    B = sorted(B)[::-1]
 
    # Traverse the arrays A and B
    for i in range(N):
 
        # If A[i] + B[i] exceeds X
        if (A[i] + B[i] > X):
 
            # Rearrangement not possible,
            # set flag to false
            flag = False
            break
 
    # If flag is true
    if (flag):
        print("Yes")
 
    # Otherwise
    else:
        print("No")
 
# Driver Code
if __name__ == '__main__':
    A = [ 1, 2, 3 ]
    B = [ 1, 1, 2 ]
    X = 4
    N = len(A)
 
    # Function Call
    rearrange(A, B, N, X)
 
# This code is contributed by mohit kumar 29

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for the above approch
using System;
using System.Collections.Generic;
class GFG
{
 
  // Function to check if elements
  // of B[] can be rearranged
  // such that A[i] + B[i] <= X
  static void rearrange(int[] A, int[] B,
                        int N, int X)
  {
 
    // Checks the given condition
    bool flag = true;
 
    // Sort A[] in ascending order
    Array.Sort(A);
 
    // Sort B[] in descending order
    Array.Sort(B);
 
    // Traverse the arrays A[] and B[]
    for (int i = 0; i < N; i++)
    {
 
      // If A[i] + B[i] exceeds X
      if (A[i] + B[N - 1 - i] > X)
      {
 
        // Rearrangement not possible,
        // set flag to false
        flag = false;
        break;
      }
    }
 
    // If flag is true
    if (flag == true)
      Console.WriteLine("Yes");
 
    // Otherwise
    else
      Console.WriteLine("No");
  }
 
  // Driver Code
  public static void Main()
  {
    int []A = { 1, 2, 3 };
    int []B = { 1, 1, 2 };
    int X = 4;
    int N = A.Length;
 
    // Function Call
    rearrange(A, B, N, X);
  }
}
 
// This code is contributed by AnkThon

chevron_right


Output: 

Yes

 

Time Complexity: O(N*log N)
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :