演算法筆記_163:演算法提高 最大乘積(Java)

來源:互聯網
上載者:User

標籤: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)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.