We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
这道题一开始完全想不到二分,不知道怎么应用二分。
这时候要用反向思维,把答案作为二分的轴。
先要排序,排除掉数组元素位置的影响。因为目的是找到之前差值大于等于这个轴的元素。
同时注意l包含,r不包含,所有r左移是r=mid;返回值直接是l-1。
r=mid
class Solution { public int maximumTastiness(int[] price, int k) { Arrays.sort(price); int l = 0, r = 1000000000; while (l < r) { int mid = (l + r) >> 1; if (check(price, k, mid)) { l = mid + 1; } else { r = mid; } } return l - 1; } boolean check(int[] price, int k, int mid) { int cnt = 1; int last = price[0]; int kk = 1; while (kk < price.length && cnt < k) { if (price[kk] - last >= mid) { ++cnt; last = price[kk]; } ++kk; } return cnt == k; } }
tips:
The text was updated successfully, but these errors were encountered:
No branches or pull requests
2517. Maximum Tastiness of Candy Basket
相关题目
这道题一开始完全想不到二分,不知道怎么应用二分。
这时候要用反向思维,把答案作为二分的轴。
先要排序,排除掉数组元素位置的影响。因为目的是找到之前差值大于等于这个轴的元素。
同时注意l包含,r不包含,所有r左移是
r=mid
;返回值直接是l-1。tips:
The text was updated successfully, but these errors were encountered: