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

简述:

输入一个字符串,切分成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 initialize
		int [][]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 process
		for(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 substring
				max = 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 j
	private Integer ConvToInt(String str, int i, int j){
		return Integer.parseInt(str.substring(i, j + 1));
	}
}

输出:



你可能感兴趣的:(输入数字组成的字符串,取k切分后的最大K乘积)