uva - 787 - Maximum Sub-sequence Product Solution
Simple dynamic problem!!!
-- Take a 2D array size [105][105]
-- calculate all set of product and store in array for future use.
-- First fill diagonal element with input array elements.
-- Then traverse diagonal wise, element value is array[i][j]= array[i][i]*array[i+1][j];
traversing end point at reaching array[0][n-1]; calculate max after calculating each product.
import java.math.BigInteger;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
BigInteger max=BigInteger.valueOf(-999999);
BigInteger [][] arr=new BigInteger[105][105];
int x,n,i,j,y;
n=1;
while(sc.hasNext()){
x=sc.nextInt();
if(x!=-999999){
arr[n][n]=BigInteger.valueOf(x); // fill diagonal element
if(arr[n][n].compareTo(max)==1){
max=arr[n][n];
}
n++;
continue;
}
n--;
x=1;
for(i=1;i<n;i++){
x++;
y=x;
for(j=1;j<=n-i;j++){
arr[j][y]=arr[j][j].multiply(arr[j+1][y]); // calculate product at diagonal wise
if(arr[j][y].compareTo(max)==1){
max=arr[j][y];
}
y++;
}
}
System.out.println(max);
n=1;
max=BigInteger.valueOf(-999999);
}
}
}
-- Take a 2D array size [105][105]
-- calculate all set of product and store in array for future use.
-- First fill diagonal element with input array elements.
-- Then traverse diagonal wise, element value is array[i][j]= array[i][i]*array[i+1][j];
traversing end point at reaching array[0][n-1]; calculate max after calculating each product.
import java.math.BigInteger;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
BigInteger max=BigInteger.valueOf(-999999);
BigInteger [][] arr=new BigInteger[105][105];
int x,n,i,j,y;
n=1;
while(sc.hasNext()){
x=sc.nextInt();
if(x!=-999999){
arr[n][n]=BigInteger.valueOf(x); // fill diagonal element
if(arr[n][n].compareTo(max)==1){
max=arr[n][n];
}
n++;
continue;
}
n--;
x=1;
for(i=1;i<n;i++){
x++;
y=x;
for(j=1;j<=n-i;j++){
arr[j][y]=arr[j][j].multiply(arr[j+1][y]); // calculate product at diagonal wise
if(arr[j][y].compareTo(max)==1){
max=arr[j][y];
}
y++;
}
}
System.out.println(max);
n=1;
max=BigInteger.valueOf(-999999);
}
}
}
Comments
Post a Comment