Leetcode | 5-21| 每日一题

2769. 找出最大的可达成数字

考点: 暴力 数学式子计算 思维

在这里插入图片描述

题解

通过式子推导: 第一想法是二分确定区间在区间内进行查找是否符合条件的, 本题最关键的便是 条件确定 ,
第二种方法: 一般是通过数学公式推导的,这种题目我称为数学式编程题

代码

  1. 条件判断式
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 减少, 因为这样才能确定右区间第一个满足条件的答案

  1. 数学公式
class Solution {
    
    
public:
    int theMaximumAchievableX(int num, int t) {
    
    
        return num + 2 * t;
    }
};

猜你喜欢

转载自blog.csdn.net/2303_79299383/article/details/139104991