K Items With the Maximum Sum | leet code | Solution | javascript

K-items with maximum sum

Problem statement 

There is a bag that consists of items, each item has a number 1, 0, or -1 written on it.

You are given four non-negative integers numOnesnumZerosnumNegOnes, and k.

The bag initially contains:

  • numOnes items with 1s written on them.
  • numZeroes items with 0s written on them.
  • numNegOnes items with -1s written on them.

We want to pick exact k items among the available items. Return the maximum possible sum of numbers written on the items.


Approach -1 


So in this problem statement, we have to find the max sum of the K elements we have given the number of one, number of zero, and number of minus -1, and the k  which is the number of elements we have to do addition. 




var kItemsWithMaximumSum = function(numOnes, numZeros, numNegOnes, k) {

let arr=[] // Taking and empty array to store the value
of zero,one and
// minus one. example, [1,0,-1]

for(let i=0; i<=numOnes-1; i++){
arr.push(1) // here we are running a for loop till
the numOne size
                     // and pushing the 1 to the array   
}
for(let i=0; i<=numZeros-1; i++){
arr.push(0)// here we are running a for loop till
the numZero size
                    // and pushing the zero
}

for(let i=0; i<=numNegOnes-1; i++){
arr.push(-1) // here we are running a for loop
till the numNegZero
                    // and pushing the -1
}
let sum=0; // taking sum variable to store the sum of elements
for(let i=0;i<=arr.length-1; i++){

if(i>k-1){ // checking the condition here we
are checking the
break; // the condition and
stoping the process
}
else{
sum+=arr[i] // adding the arr[i] value
}
}

return sum; // returning the value
};


kItemsWithMaximumSum(3,2,1,2)

console.log(kItemsWithMaximumSum(3,2,1,2))



// run time is high





Second Approach



// second approach




var kItemsWithMaximumSum = function(numOnes, numZeros, numNegOnes, k) {

if(k<=numOnes){

return k;
}else if(k>numOnes&& k<=numZeros+numOnes){
return numOnes
}
else if(k>numOnes+numZeros){
let res=numOnes
let i=numOnes+numZeros+1
while(i<=k){
res+=-1;
i++;
}
return res
}

};




// high runtime 87 ms


Third Approach


var kItemsWithMaximumSum = function(numOnes, numZeros, numNegOnes, k) {

let i=1;
let res=0;
while(i<=k){
if(i<=numOnes){
res+=1
}else if(i>numOnes&&i<=numOnes+numZeros){

res+=0
}else if(i>numOnes+numZeros && i<=k){
res+=-1
}
i++
}
return res

};

// Runtime 74 ms


Fourth Approach



var kItemsWithMaximumSum = function(numOnes, numZeros, numNegOnes, k) {

if(k<=numOnes){
return k
}
else if(k>numOnes&&k<=numZeros+numOnes){
return numOnes
}
else if(k>numOnes+numZeros){
let sum= numOnes+numZeros
return numOnes + ((k-sum)*-1)
//return numOnes + (res)
}

};


// runtime 72 ms




More Problems




Post a Comment

Previous Post Next Post