Minimum count of elements to be inserted in Array to form all values in [ 1 , K ] using subset sum | Function to find the count of minimum elements to be inserted to form every number in a range ; Stores the count of numbers needed ; Stores the numbers upto which every numbers can be formed ; Stores the index of the array arr [ ] ; Iterate until requiredSum is less than or equal to K ; If i is less than N and requiredSum is greater than or equal to arr [ i ] ; Increment requiredSum by arr [ i ] ; Increment i by 1 ; Otherwise ; Increment count by 1 ; Increment requiredSum by requiredSum ; Return result ; Input ; Function Call
function minElements ( arr , N , K ) { let count = 0 ; let requiredNum = 1 ; let i = 0 ; while ( requiredNum <= K ) { if ( i < N && requiredNum >= arr [ i ] ) { requiredNum += arr [ i ] ; i ++ ; } else { count ++ ; requiredNum += requiredNum ; } } return count ; } let arr = [ 1 , 3 ] ; let K = 6 ; let N = arr . length ; document . write ( minElements ( arr , N , K ) + " " ) ;