Skip to content
Related Articles

Related Articles

Improve Article

Minimum number of array indices required to be selected to make the sum of a set greater than another

  • Last Updated : 05 Aug, 2021

Given two arrays arr[] and brr[] of size N and an integer K. Consider two sets A, contains K initially, and B, initially empty. In each operation, an index is required to be selected. For every selected index, say i, arr[i] and brr[i] is added to B. For every unselected index, arr[i] is added to A. The task is to find the minimum number of indices required to be selected to make sum of B greater than sum of A. If it is not possible to do so, then print -1.

Examples:

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.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input: arr[] = {3, 2, 5, 6}, brr[] = {4, 4, 2, 3}, K = 12   
Output: 3
4 3 1
Explanation: Indices 2, 3 and 0 are selected. Sum of B = arr[0] + brr[0] + arr[2] + brr[2] + arr[3] + brr[3] = 3 + 4 + 5 + 2 + 6 + 3 = 23. Sum of A = K + arr[1] = 12 + 2 = 14.



Input: arr[] = {3, 2, 5, 6}, brr[] = {4, 4, 2, 3}, K = 34
Output: -1

Approach: The idea is to use a Greedy Approach. Follow the steps below to solve the problem:

  • Initialize a vector of pair, B[] to keep track of indexes.
  • Initialize a variable, A with K to store the value of set A.
  • Traverse the array arr[] using the variable i,
    • Add the value arr[i] to A, if the index was not chosen.
    • Insert {brr[i] + 2 * arr[i], i} as a pair in vector B.
  • Sort vector B in decreasing order.
  • Initialize a vector, ans to store the indexes that are chosen.
  • Run a while loop and keep on choosing the indices until A’s value is bigger than B.
  • If all indexes are chosen but B’s value is still less than A, print “-1”.
  • Otherwise, print the size of the vector ans as the minimum number of moves.
  • Traverse the vector, ans, and print the chosen indices.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to print the minimum number
// of indices required to be selected
void numberOfIndexes(int arr[], int brr[],
                     int N, int K)
{
    // Declare vector to keep track of indexes
    vector<pair<int, int> > B;
 
    // Set A contains K
    int A = K;
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
 
        // Adding value that set A can
        // get if no index was chosen
        A += arr[i];
 
        // Insert as B's value
        B.push_back({ brr[i] + 2 * arr[i], i });
    }
 
    // Sort the vector
    sort(B.begin(), B.end());
 
    // Reverse the vector
    reverse(B.begin(), B.end());
 
    int tot = 0, idx = 0;
 
    // Stores chosen indexes
    vector<int> ans;
 
    // Keep on choosing more indices until
    // B's value is bigger than A or stop
    // incase all the indexes is chosen
    while (A >= tot && idx < B.size()) {
 
        // Update tot
        tot += B[idx].first;
 
        // Update ans
        ans.push_back(B[idx].second);
 
        // Increment idx
        idx++;
    }
 
    // If all indices are selected and
    // sum of B is less than sum of A
    if (tot <= A) {
        cout << -1 << endl;
        return;
    }
 
    // Print the minimum number of indices
    cout << ans.size() << endl;
 
    // Print chosen indices
    for (auto c : ans)
        cout << c + 1 << " ";
}
 
// Driver Code
int main()
{
    // Given arrays
    int arr[] = { 3, 2, 5, 6 };
    int brr[] = { 4, 4, 2, 3 };
 
    // Size of the array
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Given value of K
    int K = 12;
 
    // Function Call
    numberOfIndexes(arr, brr, N, K);
 
    return 0;
}

Python3




# Python 3 program for the above approach
 
# Function to print the minimum number
# of indices required to be selected
def numberOfIndexes(arr, brr, N, K):
   
    # Declare vector to keep track of indexes
    B = []
 
    # Set A contains K
    A = K
 
    # Traverse the array
    for i in range(N):
       
        # Adding value that set A can
        # get if no index was chosen
        A += arr[i]
 
        # Insert as B's value
        B.append([brr[i] + 2 * arr[i], i])
 
    # Sort the vector
    B.sort()
 
    # Reverse the vector
    B = B[::-1]
    tot = 0
    idx = 0
 
    # Stores chosen indexes
    ans = []
 
    # Keep on choosing more indices until
    # B's value is bigger than A or stop
    # incase all the indexes is chosen
    while (A >= tot and idx < len(B)):
       
        # Update tot
        tot += B[idx][0]
 
        # Update ans
        ans.append(B[idx][1])
 
        # Increment idx
        idx += 1
 
    # If all indices are selected and
    # sum of B is less than sum of A
    if (tot <= A):
        print(-1)
        return
 
    # Print the minimum number of indices
    print(len(ans))
 
    # Print chosen indices
    for c in ans:
        print(c + 1,end = " ")
 
# Driver Code
if __name__ == '__main__':
   
    # Given arrays
    arr = [3, 2, 5, 6]
    brr = [4, 4, 2, 3]
 
    # Size of the array
    N = len(arr)
 
    # Given value of K
    K = 12
 
    # Function Call
    numberOfIndexes(arr, brr, N, K)
     
    # This code is contributed by SURENDRA_GANGWAR.

Javascript




<script>
 
// JavaScript program for the above approach
 
// Function to print the minimum number
// of indices required to be selected
function numberOfIndexes(arr, brr, N, K) {
  // Declare vector to keep track of indexes
  let B = [];
 
  // Set A contains K
  let A = K;
 
  // Traverse the array
  for (let i = 0; i < N; i++) {
    // Adding value that set A can
    // get if no index was chosen
    A += arr[i];
 
    // Insert as B's value
    B.push([brr[i] + 2 * arr[i], i]);
  }
 
  // Sort the vector
 
  // Reverse the vector
  B.sort((a, b) => a[0] - b[0]).reverse();
 
 
  let tot = 0,
    idx = 0;
 
  // Stores chosen indexes
  let ans = [];
 
  // Keep on choosing more indices until
  // B's value is bigger than A or stop
  // incase all the indexes is chosen
  while (A >= tot && idx < B.length) {
    // Update tot
    tot += B[idx][0];
 
    // Update ans
    ans.push(B[idx][1]);
 
    // Increment idx
    idx++;
  }
 
  // If all indices are selected and
  // sum of B is less than sum of A
  if (tot <= A) {
    document.write(-1 + "<br>");
    return;
  }
 
  // Print the minimum number of indices
  document.write(ans.length + "<br>");
  // Print chosen indices
  for (let c of ans) document.write(Number(c) + 1 + " ");
}
 
// Driver Code
 
// Given arrays
let arr = [3, 2, 5, 6];
let brr = [4, 4, 2, 3];
 
// Size of the array
let N = arr.length;
 
// Given value of K
let K = 12;
 
// Function Call
numberOfIndexes(arr, brr, N, K);
 
</script>
Output: 
3
4 3 1

 

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

 




My Personal Notes arrow_drop_up
Recommended Articles
Page :