Largest integers with sum of setbits at most K in Java

Finding the greatest number of values that may be chosen from the array so that the total number of 1s in their binary representation is at most K is the task when an array of integers nums[] and a positive integer K is given.

Example 1:

Input:

int arr[] = {1, 3, 7, 8, 9};

int K = 6;

Output:

The total number of values with sum of setbits atmost K is 3

Explanation:

For the given array {1, 3, 7, 8, 9}, considering the total of the 1s in the binary representation of 1, 3, and 7 is 6, which is equal to K, the greatest number of numbers that can be chosen is 3.

Example 2:

Input:

int arr[] = {2, 5, 6, 10, 12};

int K = 5;

Output:

The total number of values with sum of setbits atmost K is 3

Explanation:

For the given array {2, 5, 6, 10, 12}, considering the total of the 1s in the binary representation of 2, 5, and 6 is 5, which is equal to K, the greatest number of numbers that can be chosen is 3.

Example 3:

Input:

int arr[] = {3, 4, 5, 15, 31};

int K = 8;

Output:

The total number of values with sum of setbits atmost K is 4

Explanation:

For the given array {3, 4, 5, 15, 31}, considering the total of the 1s in the binary representation of 3, 4, 31 and 15 is 8, which is equal to K, the greatest number of numbers that can be chosen is 4.

Approach: Using Dynamic Programming

Algorithm:

Step 1: Create a two-dimensional array called dp. Its number of integers that can be chosen from the first i elements of the array so that the total number of 1s in their binary representation is at most j is represented by the array's dp[i][j] variable.

Step 2: The recursive formula can be used to fill the dp array:

Step 2.1: If bit_sum is the number of 1s in the binary form of nums[i - 1], then dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - bit_sum] + 1) and so on.

Step 3: dp[n][k], where n is the nums array's length, should be returned.

Implementation:

FileName: LargestIntegersSum.java

Output:

 
The total number of values with sum of setbits atmost K is 3

Complexity Analysis:

The above code's time complexity is O(N * K), where K is the given integer, and N is the length of the nums array. The Space Complexity is also O(N * K), given that a two-dimensional array of size N * K is used.