题解 | #买苹果#

买苹果

https://www.nowcoder.com/practice/61cfbb2e62104bc8aa3da5d44d38a6ef

import java.util.*;


// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextInt()) { // 注意 while 处理多个 case
            // 完全背包
            int n = in.nextInt();
            int[] bags = {6, 8};
            int[] dp = new int[n + 1];
            for (int i = 1; i <= n; i++) {
                dp[i] = Integer.MAX_VALUE; // 初始化为无穷大
            }
            dp[0] = 0; // 0个苹果需要0袋

            for (int i = 1; i <= n; i++) {
                for (int bag : bags) {
                    if (i >= bag && dp[i - bag] != Integer.MAX_VALUE) {
                        dp[i] = Math.min(dp[i], dp[i - bag] + 1);
                    }
                }
            }

            System.out.print(dp[n] == Integer.MAX_VALUE ? -1 : dp[n]);
        }
    }
}

全部评论

相关推荐

爱读书的放鸽子能手很...:刷个两端实习,冲春招,流水线什么时候不能去
我的秋招日记
点赞 评论 收藏
分享
牛客41406533...:回答他在课上学,一辈子待在学校的老教授用三十年前的祖传PPT一字一句的讲解,使用谭浩强红皮书作为教材在devc++里面敲出a+++++a的瞬间爆出114514个编译错误来学这样才显得专业
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务