標籤:static ref system family get 絕對值 參考資料 藍橋杯 imp
目錄
1 問題描述
2 解決方案
1 問題描述問題描述 對於n個數,從中取出m個數,如何取使得這m個數的乘積最大呢?輸入格式 第一行一個數表示資料群組數
每組輸入資料共2行:
第1行給出總共的數位個數n和要取的數的個數m,1<=n<=m<=15,
第2行依次給出這n個數,其中每個數位範圍滿足:a[i]的絕對值小於等於4。輸出格式 每組資料輸出1行,為最大的乘積。範例輸入1
5 5
1 2 3 4 2範例輸出
48
2 解決方案
具體代碼如下:
import java.util.ArrayList;import java.util.Collections;import java.util.Scanner;public class Main { public static long n, m, temp; public static ArrayList<Long> list = new ArrayList<Long>();//存放輸入的數 public static ArrayList<Long> result = new ArrayList<Long>(); public void getResult() { Collections.sort(list); for(int i = 0, j = list.size() - 1;m > 0;) { if(m >= 2) { long a1 = list.get(i) * list.get(i + 1); long a2 = list.get(j) * list.get(j - 1); if(a2 > a1) { temp *= list.get(j); j--; m--; } else { temp *= a1; i = i + 2; m = m - 2; } } else { if(m == 1) { temp *= list.get(j); j--; m--; } } } result.add(temp); } public static void main(String[] args) { Main test = new Main(); Scanner in = new Scanner(System.in); int t = in.nextInt(); while(t > 0) { t--; n = in.nextLong(); m = in.nextLong(); temp = 1; list.clear(); for(int i = 0;i < n;i++) { long a = in.nextLong(); list.add(a); } test.getResult(); } for(int i = 0;i < result.size();i++) System.out.println(result.get(i)); }}
參考資料:
1. 藍橋杯 演算法提高 最大乘積
演算法筆記_163:演算法提高 最大乘積(Java)