Problem · Sorting

Array Subsets 🐿️ (Frontend)

Learn this problem
MediumIBMINTERNOA
See IBM hiring insights

Problem statement

Given an integer array, divide the array into 2 subsets A and B while respecting the following conditions:

  • The intersection of A and B is null.
  • The union A and B is equal to the original array.
  • The number of elements in subset A is minimal.
  • The sum of A's elements is greater than the sum of B's elements.
  • Return the subset A in increasing order where the sum of A's elements is greater than the sum of B's elements. If more than one subset exists, return the one with the maximal sum.

    Function

    subsetA(arr: int[]) → int[]

    Complete the function subsetA in the editor.

    subsetA has the following parameter(s):

    • int arr[]: an integer array

    Returns

    int[]: an integer array with the values of subset A.

    Examples

    Example 1

    arr = [5, 3, 2, 4, 1, 2]return = [4, 5]
    The subset of A that satisfies the conditions is [4, 5]:
  • A is minimal (size 2)
  • Sum(A) = (4 + 5) = 9 > Sum(B) = (1 + 2 + 2 + 3) = 8
  • The intersection of A and B is null and their union is equal to arr.
  • The subset A with the maximal sum is [4, 5].
  • Example 2

    arr = [4, 2, 5, 1, 6]return = [5, 6]
    The subset of A that satisfies the conditions is [5, 6]:
  • A is minimal (size 2)
  • Sum(A) = (5 + 6) = 11 > Sum(B) = (1 + 2 + 4) = 7
  • Sum(A) = (4 + 6) = 10 > Sum(B) = (1 + 2 + 5) = 8
  • The intersection of A and B is null and their union is equal to arr.
  • The subset A with the maximal sum is [5, 6].
  • Constraints

    • 1 ≤ n ≤ 105
    • 1 ≤ arr[i] ≤ 105 (where 0 ≤ i < n)

    More IBM problems

    drafts saved locally
    public int[] subsetA(int[] arr) {
        // write your code here
    }
    
    arr[5, 3, 2, 4, 1, 2]
    expected[4, 5]
    checking account