Question: Please help, I wrote a program that is already finished. It just needs to be modified so that it prompts the user to enter the
Please help,
I wrote a program that is already finished. It just needs to be modified so that it prompts the user to enter the list of input. The purpose of this program is to find the max subsequence sum for the four algorithm functions already made. For example, the inputs of -2,11, -4, 13, -5, -2 is 20 for all four functions.
public static void main(String[] args) { // TODO Auto-generated method stub Scanner sdk = new Scanner(System.in); // System.out.println("enter number of elements"); // int input = sdk.nextInt(); int b[ ] = {-2,11, -4, 13, -5, -2}; // int b[] = new int[input]; // System.out.println("Enter the" + userInput + "numbers now"); // for(int i = 0; i < b.length; i++){ ; // b[i] = sdk.nextInt(); // System.out.println("These are the numbers you have entered"); //
System.out.println( "Max sum for freshmam alg is " + freshmanAlg(b)); System.out.println( "Max sum for sophmorn alg is " + sophmoreAlg(b)); System.out.println( "Max sum for junior alg is " + juniorAlg(b)); System.out.println( "Max sum for senior alg is " + seniorAlg(b)); }
public static int freshmanAlg( int a[]) { int input = a[0]; int maxSum = 0;
for( int i = 0; i < a.length; i++ ) for( int j = i; j < a.length; j++ ) { int thisSum = 0;
for( int k = i; k <= j; k++ ) thisSum += a[ k ];
if( thisSum > maxSum ) maxSum = thisSum; }
return maxSum; }
public static int sophmoreAlg( int a[] ) { int maxSum = 0;
for( int i = 0; i < a.length; i++ ) { int thisSum = 0; for( int j = i; j < a.length; j++ ) { thisSum += a[ j ];
if( thisSum > maxSum ) maxSum = thisSum; } }
return maxSum; }
private static int maxSumRec( int [ ] a, int left, int right ) { if( left == right ) // Base case if( a[ left ] > 0 ) return a[ left ]; else return 0;
int center = ( left + right ) / 2; int maxLeftSum = maxSumRec( a, left, center ); int maxRightSum = maxSumRec( a, center + 1, right );
int maxLeftBorderSum = 0, leftBorderSum = 0; for( int i = center; i >= left; i-- ) { leftBorderSum += a[ i ]; if( leftBorderSum > maxLeftBorderSum ) maxLeftBorderSum = leftBorderSum; }
int maxRightBorderSum = 0, rightBorderSum = 0; for( int i = center + 1; i <= right; i++ ) { rightBorderSum += a[ i ]; if( rightBorderSum > maxRightBorderSum ) maxRightBorderSum = rightBorderSum; }
return max3( maxLeftSum, maxRightSum, maxLeftBorderSum + maxRightBorderSum ); }
public static int juniorAlg( int [ ] a ) { return maxSumRec( a, 0, a.length - 1 ); }
private static int max3( int a, int b, int c ) { return a > b ? a > c ? a : c : b > c ? b : c; }
public static int seniorAlg( int [ ] a ) { int maxSum = 0, thisSum = 0;
for( int j = 0; j < a.length; j++ ) { thisSum += a[ j ];
if( thisSum > maxSum ) maxSum = thisSum; else if( thisSum < 0 ) thisSum = 0; }
return maxSum; } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
