I did it similarly but I skipped the Binary Search approach.
Step 0:
return k if n==1
Step 1:
realize that for values 0, 1, 3, 7, 15, 31, … 2^x-1, the set bits are maximized and that you want to fill the array with these numbers. (Reason: there is no number between(exclusive), for example, 15 and 31 that has more set bits than 15)
Step 2:
Example: n=5, k=34
now we find which (2^x-1)-number can be used to fully fill up our array. The solution is 3, because 3 * 5 <= 34 and 7 * 5 > 34.
Our array at this point: 3 3 3 3 3
Step 3:
realize that we only used 3 * 5 = 15 values of 34, we therefore have 19 to spare and can replace 3’s with 7’s.
Our array after the update: 7 7 7 7 3
Step 4:
now we take a step back. We realize that we used 31 of 34 values. We are forced to somehow use the remaining 3. This can be tricky and the only approach that always works is to remove the last 2 values and “brute force” a correct combination for the last 2 values.
Our array now: 7 7 7 ? ?
Step 5:
we brute force the last 2 values in a smart way. We need to find 2 values that sum up to 13 and have their set bits maximized. This can only happen if one number is of type (2^x-1). So we iterate over these numbers (0, 1, 3, 7, 15, 31 …), and calculate the second summand. We only care about (2^x-1) that are <= 13:
(0, 13), (1, 12), (3, 10), (7, 6). Now we find the amount of bits for each of these numbers and realize that the pair (7,6) has the most set bits.
Our final array looks like this:
7 7 7 7 6
this array has 14 set bits.
Note: step 0,3 and 4 can be done in O(1) - we can calculate the amount of our numbers with formulas.
step 2 and 5 take O(log k)