[英]How to arrange the digits of a number such that when I break it into two numbers of equal digits the product of the two numbers is maximum?
示例:如果我取數字 4544,那么當我將數字重新排列為 5444 時,我得到的最大乘積是 2376。(54 x 44) = 2376 大於 (45 x 44) = 1980
我解決這個問題的方法是用所有可能的方式排列數字,把它分成兩部分,然后從那里找到最大的產品。 是否有更快的方法來解決問題,或者是否可以采用完全不同的方法來解決問題?
這是我的代碼:
import java.util.*;
class MaxProduct
{
static int maxprod = 0;
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a no");
String n = sc.next();
permute(n,0);
System.out.println("Max Product is "+maxprod);
}
public static void permute(String s,int i)
{
if( i==s.length()-1)
{
int a = Integer.parseInt(s.substring(0,i/2+1));
int b = Integer.parseInt(s.substring(i/2+1));
maxprod = Math.max(a*b,maxprod);
}
else
{
for(int k=i;k<s.length();k++)
{
s =swapelement(s,k,i);
permute(s,i+1);
s=swapelement(s,k,i);
}
}
}
public static String swapelement(String a,int i, int j)
{
char x[]=a.toCharArray();
char ch = x[i];
x[i]=x[j];
x[j]=ch;
return String.valueOf(x);
}
}
謝謝!
我們先來看一個小問題。 對於變量x,y
,你得到
x + y = c (constant)
問題是,什么時候x*y
最大? 它可以通過多種方式解決,其中之一是微分數學。 長話短說, x
和y
彼此越近,它們的乘積就越大。
A
和B
)A>B
),分配剩余的數字以最大化B
(降序排列的較大數字)。 對於A
,我們使用剩余的較小數字從中得出最大的數字。 將較大的數字分配給B
是為了使其更接近A
。 Number = 123456 取最大位數, A = 6 and B = 5
。 現在,我們將貪婪地最大化B
,因此數字變為A = 621 and B = 543
Number = 88871256 取最大位數, A = 8 and B = 8
。 由於它們仍然相等,我們重復步驟 1,因此A = 88 and B = 87
。 現在,我們將貪婪地最大化B
,因此數字變為A = 8821 and B = 8765
。
由於這是一個相當簡單的問題,因此添加任何實現似乎都是不必要的。
一種方法可以是兩個找到兩個最高數字,並將它們保留在最左邊的位置,然后相反地保留第二位。
例如:
如果你有數字 1234,最高數字是 3 和 4,所以讓他們先保留 position,剩下的 2 做同樣的事情,所以數字將是:
(41*32) = 1312
所以在這里你看到 1312 是可能的最高數字
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.