贪心买橘子|刷题打卡

177 阅读1分钟

掘金团队号上线,助你 Offer 临门! 点击 查看详情

一、题目描述:

image.png

二、思路分析:

假设橘子总数为n,则n = x * 3 + y * 5时,可以恰好购买,否则返回-1。

为了使袋数最少,尽可能多的使用更多的5,即尽可能y最大,简单的贪心算法

三、AC 代码:

#include<iostream>
using namespace std;
int canbuy(int N){
    // 计算不考虑能否成功的情况下,最多的一袋5个的数量
    int num = N / 5;
    int tmp = N - 5 * num;
    //if(tmp % 3== 0)return tmp / 3 + num;
    for(;num >= 0 ; num--,tmp += 5){
        if(tmp % 3 == 0)return tmp / 3 + num;
    }
    return -1;
}
int main(){
    cout<< "3:" << canbuy(3) << endl;
    cout<< "4:" << canbuy(4) << endl;
    cout<< "14:" << canbuy(14) << endl;
    cout<< "60:" << canbuy(60) << endl;
    cout<< "100:" << canbuy(100) << endl;
    cout<< "27:" << canbuy(27) << endl;
}

四、总结:

主要是把握贪心的思想,想明白尽可能用5就可以了