应该使用给定的金额购买哪些产品:Hackerrank?

I am writing code for the challenge given here

我已经为该问题编写了代码。但是,它在除三个以外的大多数测试用例中都可以运行。他们显示的错误消息是“您的代码未在时限内执行”。显然,代码需要优化。谁能告诉我该怎么做?

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class Solution {

    // Complete the whatFlavors function below.
    static void whatFlavors(int[] cost, int money) {

         int baseItem=0, comparedItem = 0,totalAmount=0, chosenFlavour1=0,
                chosenFlavour2=0,flag=0;
        for(int i = 0 ; i<(cost.length-1); i++)
        {
            baseItem = cost[i];
            for(int j = (i+1); j< (cost.length);j++)
            {
                comparedItem= cost[j];
                totalAmount = baseItem + comparedItem;

                if(totalAmount == money)
                {
                    chosenFlavour1 = i;
                    chosenFlavour2 = j;
                    flag = 1;
                    break;
                }

            }

            if(flag == 1)
            {
               break; 
            }
        }

        chosenFlavour1++;
        chosenFlavour2++;
        System.out.println(chosenFlavour1+" "+chosenFlavour2);


    }

    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        int t = scanner.nextInt();
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        for (int tItr = 0; tItr < t; tItr++) {
            int money = scanner.nextInt();
            scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

            int n = scanner.nextInt();
            scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

            int[] cost = new int[n];

            String[] costItems = scanner.nextLine().split(" ");
            scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

            for (int i = 0; i < n; i++) {
                int costItem = Integer.parseInt(costItems[i]);
                cost[i] = costItem;
            }

            whatFlavors(cost, money);
        }

        scanner.close();
    }
}
评论