Input: numOnes =3, numZeros =2, numNegOnes =0, k =2Output: 2Explanation: We have a bag of items with numbers written on them {1,1,1,0,0}. We take 2 items with1 written on them and get a sum in a total of 2.It can be proven that 2is the maximum possible sum.
Input: numOnes =3, numZeros =2, numNegOnes =0, k =4Output: 3Explanation: We have a bag of items with numbers written on them {1,1,1,0,0}. We take 3 items with1 written on them, and 1 item with0 written on it, and get a sum in a total of 3.It can be proven that 3is the maximum possible sum.
To maximize the sum, always pick as many 1’s as possible, then 0’s, and only pick -1’s if needed. This is because 1 > 0 > -1, and we want the largest possible sum.
classSolution {
public:int kItemsWithMaximumSum(int numOnes, int numZeros, int numNegOnes, int k) {
int ans =0;
int take1 = min(numOnes, k);
ans += take1;
k -= take1;
int take0 = min(numZeros, k);
k -= take0;
ans -= k; // remaining k are -1's
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
funckItemsWithMaximumSum(numOnesint, numZerosint, numNegOnesint, kint) int {
ans:=0take1:= min(numOnes, k)
ans+=take1k-=take1take0:= min(numZeros, k)
k-=take0ans-=kreturnans}
func min(a, bint) int { ifa < b { returna }; returnb }
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
publicintkItemsWithMaximumSum(int numOnes, int numZeros, int numNegOnes, int k) {
int ans = 0;
int take1 = Math.min(numOnes, k);
ans += take1;
k -= take1;
int take0 = Math.min(numZeros, k);
k -= take0;
ans -= k;
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
funkItemsWithMaximumSum(numOnes: Int, numZeros: Int, numNegOnes: Int, k: Int): Int {
var ans = 0var rem = k
val take1 = minOf(numOnes, rem)
ans += take1
rem -= take1
val take0 = minOf(numZeros, rem)
rem -= take0
ans -= rem
return ans
}
}
1
2
3
4
5
6
7
8
classSolution:
defkItemsWithMaximumSum(self, numOnes: int, numZeros: int, numNegOnes: int, k: int) -> int:
ans = min(numOnes, k)
k -= ans
take0 = min(numZeros, k)
k -= take0
ans -= k
return ans
1
2
3
4
5
6
7
8
9
10
impl Solution {
pubfnk_items_with_maximum_sum(num_ones: i32, num_zeros: i32, num_neg_ones: i32, k: i32) -> i32 {
letmut ans = num_ones.min(k);
letmut rem = k - ans;
let take0 = num_zeros.min(rem);
rem -= take0;
ans -= rem;
ans
}
}