• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
金大鑫要坚持
博客园    首页    新随笔    联系   管理    订阅  订阅

虚拟游戏理财 算法题

华为OD C卷 虚拟游戏理财

暴力枚举法。更好的方法是动态规划。菜鸡不会。

自己也写了,但是不全对,gpt写的,但是也有问题。自己修改后正确:

import java.util.*;

    public class InvestmentGame {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            int m = scanner.nextInt(); // 产品数
            int totalInvestment = scanner.nextInt(); // 总投资额
            int totalRisk = scanner.nextInt(); // 可接受的总风险
            int[] returns = new int[m]; // 产品投资回报率序列
            int[] risks = new int[m]; // 产品风险值序列
            int[] maxInvestments = new int[m]; // 最大投资额度序列

            for (int i = 0; i < m; i++) {
                returns[i] = scanner.nextInt();
            }
            for (int i = 0; i < m; i++) {
                risks[i] = scanner.nextInt();
            }
            for (int i = 0; i < m; i++) {
                maxInvestments[i] = scanner.nextInt();
            }

            List<Integer> result = optimizeInvestment(m, totalInvestment, totalRisk, returns, risks, maxInvestments);
            for (Integer investment : result) {
                System.out.print(investment + " ");
            }
        }

        public static List<Integer> optimizeInvestment(int m, int totalInvestment, int totalRisk, int[] returns, int[] risks, int[] maxInvestments) {
            List<Integer> result = new ArrayList<>();
            int maxReturn = 0;
            int[] bestInvestments = new int[m];
            for (int i = 0; i < m; i++) {
                for (int j = i + 1; j < m; j++) {
                    for (int invest1 = 0; invest1 <= maxInvestments[i]; invest1++) {
                        for (int invest2 = 0; invest2 <= maxInvestments[j]; invest2++) {
                            if (risks[i] +  risks[j] <= totalRisk && invest1 + invest2 <= totalInvestment) {
                                int totalReturn = invest1 * returns[i] + invest2 * returns[j];
                                if (totalReturn > maxReturn) {
                                    bestInvestments = new int[m];
                                    maxReturn = totalReturn;
                                    bestInvestments[i] = invest1;
                                    bestInvestments[j] = invest2;
                                }
                            }
                        }
                    }
                }
            }
            for (int investment : bestInvestments) {
                result.add(investment);
            }
            return result;
        }
    }

输入为:

5 100 10
10 20 30 40 50
3 4 5 6 10
20 30 20 40 30

输出为:
0 30 0 40 0

posted @ 2024-03-28 16:09  金大鑫要坚持  阅读(316)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3