一、题目
问题描述
题目很简单,给出N个数字,不改变它们的相对位置,在中间加入K个乘号和N-K-1个加号,(括号随便加)使最终结果尽量大。因为乘号和加号一共就是N-1个了,所以恰好每两个相邻数字之间都有一个符号。例如:
N=5,K=2,5个数字分别为1、2、3、4、5,可以加成:
1*2*(3+4+5)=24
1*(2+3)*(4+5)=45
(1*2+3)*(4+5)=45
……
输入格式
输入文件共有二行,第一行为两个有空格隔开的整数,表示N和K,其中(2<=N<=15, 0<=K<=N-1)。第二行为 N个用空格隔开的数字(每个数字在0到9之间)。
输出格式
输出文件仅一行包含一个整数,表示要求的最大的结果
样例输入
5 2
1 2 3 4 5
样例输出
120
样例说明
(1+2+3)*4*5=120
二、分析
1、以1_2_3_4_5为例,当只有一个*号时,把它放入空闲位置,它对应以下四种情况。
(这个号把算式分成了两部分,left代表左边,right代表*右边)
(1)、1*(2+3+4+5) 此时left–>1—————— right—>(2+3+4+5)
(2)、(1+2)*(3+4+5) 此时left—>(1+2)———–right—>(3+4+5)
(3)、(1+2+3)*(4+5) 此时left—>(1+2+3)——–right—>(4+5)
(4)、(1+2+3+4)*5 此时left—->(1+2+3+4)—–right—>5
如果是这样,只要求出上述四种情况取出最大值即可确定最大算式。
用getMax{}函数代表上述求解过程。
2、如果有两个号时,应先确定第一个号的位置,然后对right进行f操作即可。
(1)、*在1后面,left:1 ——————right:getMax{2,3,4,5}
(2)、*在2后面,left:1+2—————-right:getMax{3,4,5}
(3)、*在3后面,left:1+2+3————-right:getMax{4,5}
(4)、*在4后面,left:1+2+3+4———-right:getMax{5}
3、根据1和2便可得出状态转移方程
getMax(int[] A, int start, int mulCount)代表向数组A中从start位置开始插入mulCount个*的算式的最大值。
getSum(int[] A, int start, int end)代表从数组A的start位置开始到end位置的值。
getMax(int[] A, int start, int mulCount)=Max{ getSum(A, start, i) * getMax(A, i + 1, mulCount- 1)}
注:以上参考:http://blog.chinaunix.net/uid-26456800-id-3509246.html
public class Question116 {
public static void main(String[] args) {
Question116 test = new Question116();
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int k = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = in.nextInt();
System.out.println(test.getMax(a, 0, k));
}
/**
*
* @param a
* 存放算式元素的数组
* @param start
* @param end
* @return 从start位置到end位置的元素之和
*/
public long getSum(int[] a, int start, int end) {
long sum = 0;
for (int i = start; i <= end; i++)
sum += a[i];
return sum;
}
/**
*
* @param a
* 存放算式元素的数组
* @param start
* 插入*的起始位置
* @param mulCount
* 插入*的个数
* @return
*/
public long getMax(int[] a, int start, int mulCount) {
// 插入的*个数为0,直接求和即可
if (mulCount == 0)
return getSum(a, start, a.length - 1);
long max = 0;
for (int i = start; i < a.length - 1; i++) {
// 状态转移方程:
long tempMax = getSum(a, start, i) * getMax(a, i + 1, mulCount - 1);
max = Math.max(tempMax, max);
}
return max;
}
}
When I was young I observed that nine out of every ten things I did were failures,so I did ten times more work.