Blue Bridge Cup training algorithm largest equation

Problem Description
  Title is very simple, given N digital, do not change their relative positions, in the middle of the K multiplication and addition of NK-1 plus sign, (plus whatever parentheses) the end result is as large as possible. Because the multiplication and plus is a total of the N-1, so exactly between every two adjacent numbers have a sign. For example:
  N = 5, K = 2,5 numbers 1,2,3,4,5 respectively, may be an addition:
  . 1 2 (3 + 4 + 5) = 24
  . 1
(2 + 3) (4 + 5 ) 45 =
  (1
2 + 3) * (4 + 5) = 45
  ......
*
  
input format
  input files total two lines, the first two acts integers separated by a space, and N represents K, where (2 <= N <= 15, 0 <= K <= N-1). The second line of the N numbers separated by spaces (each number between 0 to 9).

Output format
  output file only one row contains an integer indicating a result of the required maximum

  
sample input
. 5 2
. 1 2. 5. 4. 3

Sample Output
120

Example Description
  (1 + 2 + 3) = 120 * 4 * 5


import java.util.Scanner;
public class Main {
    public static void main(String[] args) { 
        int a[]=new int[120];
        long sum[]=new long[120];    
        long f[][]=new long[120][120];
        int n,K;
        sum[0]=0; 
        Scanner sc=new  Scanner(System.in);
        n=sc.nextInt();
        K=sc.nextInt();
        for(int i=1;i<=n;i++){
            a[i]=sc.nextInt();
            sum[i]=sum[i-1]+a[i];
        }
        for(int i=1;i<=n;i++)
            f[i][0]=sum[i];
        for(int i=0;i<=n;i++){
             int t = Math.min(i - 1, K);
            for(int j=1;j<=t;j++){ 
                for(int k=2;k<=i;k++){
                    long s=sum[i]-sum[k-1];
                    f[i][j]=Math.max(f[k-1][j-1]*s, f[i][j]);
                }
            }
        }
        System.out.println(f[n][K]);

    }

}

test

Published 475 original articles · won praise 682 · views 520 000 +

Guess you like

Origin blog.csdn.net/Czhenya/article/details/104902058