在一个由n个数字组成的数字串中出入k个乘号(k>=1,k<10),将它分成k+1个整数,找出一种乘号的插入方法,使得这个k+1个整数的乘积最大。例如,对给定的数串847313926,如何插入k=5个乘号,使乘积最大?
package common.test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class Mytest15 {
static List<Integer> result = new ArrayList<Integer>();
public static void play(int n, String tempStr, String operate[], int num[],
int limit) {
if (n == num.length - 1) {
if (JudeMultiple(tempStr, limit))
result.add(CalcValue(tempStr + num[n]));
return;
}
for (int i = 0; i < 2; i++) {
String start = num[n] + "";
tempStr += start + operate[i];
play(n + 1, tempStr, operate, num, limit);
tempStr = tempStr.substring(0, tempStr.length()
- (start + operate[i]).length());
}
}
public static boolean JudeMultiple(String str, int limit) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
char temp = str.charAt(i);
if (temp == '*')
count++;
}
if (count == limit)
return true;
return false;
}
public static int CalcValue(String tempStr) {
int value = 1;
String[] str = tempStr.split("\\*");
for (int i = 0; i < str.length; i++)
value *= Integer.parseInt(str[i]);
return value;
}
public static void main(String[] args) {
int num[] = { 8, 4, 7, 3, 1, 3, 9, 2, 6 };
Scanner input =new Scanner(System.in);
int n=input.nextInt();
int limit = n;
String operate[] = {"", "*"};
play(0, "", operate, num, limit);
System.out.println(Collections.max(result));
}
}