Algorithm Note _163: Algorithm increases the maximum product (Java)

Source: Internet
Author: User

Directory

1 Problem Description

2 Solutions

  1 problem description Problem Descriptionfor the number of N, the number of M to take out, how to make this number of M product maximum? Input FormatThe first row, one number, indicates the number of data groups
each set of input data total 2 lines:
The 1th line gives the number of the total number n and the number of m,1<=n<=m<=15 to be taken,
The 2nd row gives the number of n, where each number has a range of: A[i] with an absolute value less than or equal to 4. output Formateach set of data outputs 1 rows, which is the maximum product. Sample Input1
5 5
1 2 3) 4 2Sample Output
48

2 Solutions

The specific code is as follows:

Importjava.util.ArrayList;Importjava.util.Collections;ImportJava.util.Scanner; Public classMain { Public Static LongN, m, temp;  Public Staticarraylist<long> list =NewArraylist<long> ();//store the number of inputs     Public Staticarraylist<long> result =NewArraylist<long>();  Public voidGetResult () {collections.sort (list);  for(inti = 0, j = list.size ()-1;m > 0;) {            if(M >= 2) {                LongA1 = List.get (i) * List.get (i + 1)); LongA2 = 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 voidMain (string[] args) {main test=NewMain (); Scanner in=NewScanner (system.in); intt =In.nextint ();  while(T > 0) {T--; N=In.nextlong (); M=In.nextlong (); Temp= 1;            List.clear ();  for(inti = 0;i < n;i++) {                LongA =In.nextlong ();            List.add (a);        } test.getresult (); }         for(inti = 0;i < Result.size (); i++) System.out.println (Result.get (i)); }}

Resources:

1. Blue Bridge Cup algorithm increases the maximum product

Algorithm Note _163: Algorithm increases the maximum product (Java)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.