输入数字组成的字符串,取k切分后的最大K乘积

来源:互联网 发布:手机图片扫描软件 编辑:程序博客网 时间:2024/06/05 21:09

简述:

输入一个字符串,切分成k项,选取其中最大的k项乘积,并求取最大值

如“123”切为2分,则两项最大乘积是12 * 3 = 36


算法描述:

array[ i ][ j ] = Max( array[i - 1][ m] * convToInt(str, m + 1, j] )

表示 i项 , 从0 到 j 的截取int的值 等于, i - 1项m长度的最大值 乘上, 从m 到 j, 从str截取字符串后转换为int之后的最大积


代码:

package dynamic_programming;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;public class MaximumK_Product {public static void main(String[] args) {InputStream inputStream = System.in;InputStreamReader inputStreamReader = new InputStreamReader(inputStream);BufferedReader bufferedReader = new BufferedReader(inputStreamReader);String numStr = null;System.out.print("Input the raw string: ");try{numStr = bufferedReader.readLine();}catch(IOException e){e.printStackTrace();}MaximumK_Product obj = new MaximumK_Product();System.out.println("Maximum: " + obj.getMaximumK_Product(numStr, 2));}public int getMaximumK_Product(String str, int k){int len = str.length();// to show result of k directly , so I use k+1 to initializeint [][]array = new int[k+1][len]; if(k > len)return Integer.MIN_VALUE;for(int i = 0; i < len; i++)array[1][i] = ConvToInt(str, 0, i);int max = Integer.MIN_VALUE;int temp = 0; // keep the value in processfor(int i = 2; i <= k; i++){ //i is the number of parts divided for(int j = i - 1; j < len; j++){ // j is the end of the substringmax = Integer.MIN_VALUE;for(int m = 0; m < j; m++){ // temp = array[i - 1][m] * ConvToInt(str, m + 1, j);if(temp > max)max = temp;}array[i][j] = max; //keep the max value from i to j}}return max;}//convert Integer string from position i to position jprivate Integer ConvToInt(String str, int i, int j){return Integer.parseInt(str.substring(i, j + 1));}}

输出: