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

乘积最大问题:运用动态规划
问题描述:向长度为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();
 }
}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值