3281. Maximize Score of Numbers in Ranges - Medium
前往題目
想法
- 毫無頭緒,只覺得應該要用
binary search
來做,但無從下手
思路
即便思考許久,也參考網路上解答,但還是沒有完全理解這題
Binary serach
搜尋最終的結果- 下為
0
,上為Integer.MAX_VALUE
- 每次都檢查是否這個
score
可以是答案(這裡檢查的部分就是我無法完全懂的地方)- 每次都檢查
前數 + score
是否大於當前數字 + d
,如果大於就代表這個score
是不可能的 - 通過就更新前數為
前數 + score
或當前數字
取最大值 - 全部檢查完都通過就回傳
true
- 每次都檢查
這裡我不理解為什麼這樣檢查前數 + score
是否大於當前數字 + d
就可以確保score
是valid
…
Code
class Solution {
public int maxPossibleScore(int[] start, int d) {
int l = 0, r = Integer.MAX_VALUE;
int res = 0;
Arrays.sort(start);
// Search for the possible score
while (l <= r) {
// Possible score
int mid = l + (r - l) / 2;
if (isValid(start, d, mid)) {
res = mid;
l = mid + 1;
} else {
r = mid - 1;
}
}
return res;
}
private boolean isValid(int[] nums, int d, int possibleScore) {
int prev = nums[0];
for (int i = 1; i < nums.length; ++i) {
// Exceed the maximum day
if (prev + possibleScore > nums[i] + d) return false;
// Update previous value
prev = Math.max(prev + possibleScore, nums[i]);
}
return true;
}
}
3281. Maximize Score of Numbers in Ranges - Medium
https://f88083.github.io/2024/09/12/3281-Maximize-Score-of-Numbers-in-Ranges-Medium/