Java-雙十一
題目描述
雙十一眾多商品進行打折銷售,小明想購買一些自己心儀的商品,
但由于受購買資金限制,所以他決定從眾多心意商品中購買3件,
而且想盡可能的花完資金,
現(xiàn)在請你設計一個程序幫助小明計算盡可能花費的最大資金額。
輸入描述
第一行為整型數(shù)組M,數(shù)組長度小于100,數(shù)組元素記錄單個商品的價格;
單個商品價格小于1000;
第二行輸入為購買資金的額度R;
R < 100000。
輸出描述
輸出為滿足上述條件的最大花費額度
如果不存在滿足上述條件的商品請返回-1
示例一
輸入
23,26,36,27
78
輸出
76
示例二
輸入
23,30,40
26
輸出
-1
參考解題 Java
import java.util.*;
public class Main{
?private static final List<List<Integer>> combines = new ArrayList<>();
?private static final List<Integer> combine = new ArrayList<>(3);
?private static int res = -1;
?public static void main(String[] args) {
? ?try (Scanner scanner = new Scanner(System.in)) {
? ? ?String m = scanner.nextLine();
? ? ?int r = scanner.nextInt();
? ? ?solution(m, r);
? ?}
?}
?private static void solution(String m, int r) {
? ?String[] goodsPricesString = m.split(",");
? ?int[] goodsPrices = new int[goodsPricesString.length];
? ?for (int i = 0; i < goodsPricesString.length; i++) {
? ? ?goodsPrices[i] = Integer.parseInt(goodsPricesString[i]);
? ?}
? ?Arrays.sort(goodsPrices);
? ?if (goodsPrices.length < 3 ||
? ? ? ?goodsPrices[0] + goodsPrices[1] + goodsPrices[2] > r) {
? ? ?System.out.println(-1);
? ? ?return;
? ?}
? ?takeGoods(goodsPrices, 0);
? ?combines.stream()
? ? ? ?.map(list -> sum(list))
? ? ? ?.sorted(Integer::compareTo)
? ? ? ?.forEach(sum -> {
? ? ? ? ?if (sum > res && sum <= r) {
? ? ? ? ? ?res = sum;
? ? ? ? ?}
? ? ? ?});
? ?System.out.println(res);
?}
?private static void takeGoods(int[] goodsPrices, int start) {
? ?if (combine.size() == 3) {
? ? ?combines.add(new ArrayList<>(combine));
? ? ?return;
? ?}
? ?for (int i = start; i < goodsPrices.length; i++) {
? ? ?combine.add(goodsPrices[i]);
? ? ?takeGoods(goodsPrices, i + 1);
? ? ?combine.remove(combine.size() - 1);
? ?}
?}
?private static Integer sum(List<Integer> prices) {
? ?int sum = 0;
? ?for (Integer i : prices) {
? ? ?sum += i;
? ?}
? ?return sum;
?}
}
標簽: