We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 1adeab1 commit a2eb491Copy full SHA for a2eb491
C++/maximum-tastiness-of-candy-basket.cpp
@@ -0,0 +1,34 @@
1
+// Time: O(nlogr), r is max(price) - min(price)
2
+// Space: O(1)
3
+
4
+// binary search, greedy
5
+class Solution {
6
+public:
7
+ int maximumTastiness(vector<int>& price, int k) {
8
+ const auto& check = [&](int x) {
9
+ int cnt = 0, prev = 0;
10
+ for (int i = 0, j = 0; i < size(price); ++i) {
11
+ if (prev && price[i] - prev < x) {
12
+ continue;
13
+ }
14
+ if (++cnt == k) {
15
+ break;
16
17
+ prev = price[i];
18
19
+ return cnt >= k;
20
+ };
21
22
+ sort(begin(price), end(price));
23
+ int left = 1, right = price.back() - price.front();
24
+ while (left <= right) {
25
+ const int mid = left + (right - left) / 2;
26
+ if (!check(mid)) {
27
+ right = mid - 1;
28
+ } else {
29
+ left = mid + 1;
30
31
32
+ return right;
33
34
+};
0 commit comments