2769. 找出最大的可達成數字
考點: 暴力
數學式子計算
思維
題解
通過式子推導: 第一想法是二分確定區間在區間內進行查找是否符合條件的, 本題最關鍵的便是 條件確定 ,
第二種方法: 一般是通過數學公式推導的,這種題目我稱為數學式編程題
代碼
- 條件判斷式
class Solution {
public:bool check(int num,int x,int t) {if(num + t < x - t) return false; // 為什么是這個式子?else return true; // 看代碼解釋}int theMaximumAchievableX(int num, int t) {int x = 1000; // 確定區間 注意不要太大否則會超時while(!check(num,x,t)) {x--;}return x;}
};
代碼解釋: 因為x 一定比 num 大因為要最大必然要讓 x 減少, 因為這樣才能確定右區間第一個滿足條件的答案
- 數學公式
class Solution {
public:int theMaximumAchievableX(int num, int t) {return num + 2 * t;}
};