一道算法题——乘积最大问题

来源:互联网 发布:陈赫老婆的淘宝店 编辑:程序博客网 时间:2024/06/11 07:44

乘积最大问题:运用动态规划
问题描述:向长度为N的数字串中插入r个乘号,将其分成r+1个组成部分,找出一种分法,使得这r+1个部分乘积最大。
输入:数字串的个数以及N个数字字符,以有乘号的个数r
输出:乘号的位置以及最后的乘积
 

package MaxMultiply;

public class MaxMultiply {
 private String str;
 private int num;
 
 public MaxMultiply(){
  this("4581",2);
 }
 public MaxMultiply(String str,int num){
  this.str = str;
  this.num = num;
 }
 
 String theMaxMultiply(){
  String[][] a = new String[str.length()+1][num+1];
  long temp = 0;
  String[] s = new String[2];
  String[] t = new String[2];
  for(int i=1 ; i<= str.length() ; i++){
     for(int j=0; j<= num ; j++){
         if(j == 0)
          a[i][j] =str.substring(0, i) + "#" + str.substring(0, i);
         if( (i<=j) || (i-j)>(str.length()-num) ){
             a[i][j] = "0#0";
         }else if(j>0){
          a[i][j] = a[i-1][j-1];
          for(int d=1; d<i; d++){
           s = a[i][j].split("#");
           t = a[d][j-1].split("#");
           if( (temp =Long.parseLong(t[1])*Long.parseLong(str.substring(d, i))) > Long.parseLong(s[1]))
             a[i][j]= t[0] + "*" + str.substring(d, i) + "#" + temp;
          }
         }
     }
  }
  System.out.println(a[str.length()][num]);
  return a[str.length()][num];
 }
 
 public static void main(String[] atgs){
  MaxMultiply max = new MaxMultiply();
  max.theMaxMultiply();
 }
}
 

原创粉丝点击