Open In App

Reduce sum of same-indexed elements of two arrays to less than K by rearranging the second array

Last Updated : 04 May, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// C++ program for the above approach
 
#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;
}


Java




// Java program for the above approach
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


Python3




# Python3 program for the above approach
 
# 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


C#




// C# program for the above approach
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


Javascript




<script>
 
// Javascript program of the above approach
 
// Function to check if elements
// of B[] can be rearranged
// such that A[i] + B[i] <= X
function rearrange(A, B, N, X)
{
 
    // Checks the given condition
    let flag = true;
     
    // Sort A[] in ascending order
    A.sort();
     
    // Sort B[] in descending order
    B.sort();
     
    // Traverse the arrays A[] and B[]
    for(let 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)
        document.write("Yes");
     
    // Otherwise
    else
        document.write("No");
}
 
// Driver Code
let A = [ 1, 2, 3 ];
let B = [ 1, 1, 2 ];
let X = 4;
let N = A.length;
 
// Function Call
rearrange(A, B, N, X);
 
// This code is contributed by avijitmondal1998
 
</script>


Output: 

Yes

 

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



Similar Reads

Bitwise XOR of same indexed array elements after rearranging an array to make XOR of same indexed elements of two arrays equal
Given two arrays A[] and B[] consisting of N positive integers, the task is to the Bitwise XOR of same indexed array elements after rearranging the array B[] such that the Bitwise XOR of the same indexed elements of the arrays A[] becomes equal. Examples: Input: A[] = {1, 2, 3}, B[] = {4, 6, 7}Output: 5Explanation:Below are the possible arrangement
14 min read
Minimize sum of product of same-indexed elements of two arrays by reversing a subarray of one of the two arrays
Given two equal-length arrays A[] and B[], consisting only of positive integers, the task is to reverse any subarray of the first array such that sum of the product of same-indexed elements of the two arrays, i.e. (A[i] * B[i]) is minimum. Examples: Input: N = 4, A[] = {2, 3, 1, 5}, B[] = {8, 2, 4, 3} Output: A[] = 1 3 2 5 B[] = 8 2 4 3 Minimum pro
12 min read
Rearrange two given arrays to maximize sum of same indexed elements
Given two arrays A[] and B[] of size N, the task is to find the maximum possible sum of abs(A[i] – B[i]) by rearranging the array elements. Examples: Input: A[] = {1, 2, 3, 4, 5}, B[] = {1, 2, 3, 4, 5}Output: 12Explanation: One of the possible rearrangements of A[] is {5, 4, 3, 2, 1}. One of the possible rearrangements of B[] is {1, 2, 3, 4, 4}. Th
5 min read
Rearrange two given arrays such that sum of same indexed elements lies within given range
Given two arrays arr1[] and arr2[] consisting of N positive integers and an even integer K, the task is to check if the sum of the same indexed elements in the two arrays lie in the range [K/2, K] after rearranging the given arrays or not. If it is possible to obtain such an arrangement, then print "Yes". Otherwise, print "No". Examples: Input: arr
6 min read
Construct two N-length arrays with same-indexed elements as co-prime and a difference of N in their sum
Given a positive integer N, the task is to generate two arrays of length N such that the same-indexed elements of both the arrays are co-prime and absolute difference between the sum of elements of the arrays is N. Examples: Input: N = 5Output: {1, 3, 5, 7, 9} {2, 4, 6, 8, 10}Explanation: Pairs of same-indexed elements are (1, 2), (3, 4), (5, 6), (
6 min read
Maximize sum of product of same-indexed elements of equal length subarrays obtained from two given arrays
Given two arrays arr[] and brr[] of size N and M integers respectively, the task is to maximize the sum of the product of the same-indexed elements of two subarrays of an equal length with the selected subarray from the array brr[] being reversed. Examples: Input: arr[] = {-1, 3, -2, 4, 5}, brr[] = {4, -5}Output: 26Explanation:Subarrays selected fr
13 min read
Minimum swaps of same-indexed elements required to make sum of two given arrays even
Given two arrays arr1[] and arr2[] of size N, the task is to count the minimum number of swaps of same-indexed elements from both the arrays arr1[] and arr2[] required to make the sum of all elements of both the arrays even. If it is not possible, then print "-1". Examples: Input: arr1[] = {1, 4, 2, 3}, arr2[] = {2, 3, 4, 1}Output: 0Explanation: Su
9 min read
Minimize sum of absolute differences of same-indexed elements of two given arrays by at most one replacement
Given two arrays A[] and B[] of size N each, the task is to find the minimum possible sum of absolute difference of same indexed elements of the two arrays, i.e. sum of |A[i] - B[i]| for all i such that 0 ? i &lt; N by replacing at most one element in A[] with another element of A[]. Examples: Input: A[] = {6, 4, 1, 9, 7, 5}, B[] = {3, 9, 7, 4, 2,
10 min read
Rearrange array to make Bitwise XOR of similar indexed elements of two arrays is same
Given two arrays A[] and B[] consisting of N integers (N is odd), the task is to rearrange array B[] such that for each 1 ? i ? N, Bitwise XOR of A[i] and B[i] is the same. If no such rearrangement is possible, print "-1". Otherwise, print the rearrangement. Examples: Input: A[] = {1, 2, 3, 4, 5}, B[] = {5, 4, 3, 2, 1}Output: {1, 2, 3, 4, 5}Explana
9 min read
Check if an array can be sorted by rearranging odd and even-indexed elements or not
Given an array arr[] of size N, the task is to check if it is possible to sort the array using the following operations: Swap(arr[i], arr[j]), if i &amp; 1 = 1 and j &amp; 1 = 1.Swap(arr[i], arr[j]), if i &amp; 1 = 0 and j &amp; 1 = 0. Examples: Input: arr[] = {3, 5, 1, 2, 6}Output: YesExplanation: Swap(3, 1) --&gt; {1, 5, 3, 2, 6}Swap(5, 2) --&gt;
11 min read