虛擬遊戲理財 算法題

華爲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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章