w3resource

Java: Compute the maximum value of the sum of the passing integers

Java Basic: Exercise-240 with Solution

As shown in Figure 1, arrange integers (0 to 99) as narrow hilltops. When reading such data from top to bottom, following the next rule represents a huge amount of data.
Write a Java program that computes the maximum value of the sum of the passing integers.

Input:
A series of integers separated by commas are given in diamonds. No spaces are included in each line. The input example corresponds to Figure 1. The number of lines of data is less than 100 lines.
Output: The maximum value of the sum of integers passing according to the rule on one line.

Pictorial Presentation:

Java Basic Exercises: Restore the original string by entering the compressed string with this rule.

Sample Solution:

Java Code:

 import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main{
 
    public static void main(String[] args) {
		System.out.println("Input the numbers (ctrl+c to exit):");
        Scanner sc = new Scanner(System.in);
        List<String> l = new ArrayList<String>();
        while(sc.hasNext())l.add(sc.next());
        int n = l.size();
        int[][] a = new int[n][];
        for(int i=0;i<n;i++){
            String[] s = l.get(i).split(",");
            int k = s.length;
            a[i] = new int[k];
            for(int j=0;j<k;j++)a[i][j]=Integer.parseInt(s[j]);
        }
        int[] sd = {a[0][0]};
        for(int i=1;i<n;i++){
            int[] tmp = new int[a[i].length];
            for(int j=0;j<tmp.length;j++){
                if(i<=n/2){
                    if(j==0)tmp[j]=sd[j]+a[i][j];
                    else if(j==tmp.length-1)tmp[j]=sd[j-1]+a[i][j];
                    else tmp[j]=Math.max(sd[j-1]+a[i][j], sd[j]+a[i][j]);
                }
                else{
                    tmp[j] = Math.max(sd[j]+a[i][j], sd[j+1]+a[i][j]);
                }
            }
            sd = tmp;
        }
		System.out.println("Maximum value of the sum of integers passing according to the rule on one line.");
        System.out.println(sd[0]);
    }
}

Sample Output:

Input the numbers (ctrl+c to exit):
8
4,9
9,2,1
3,8,5,5
5,6,3,7,6
3,8,5,5
9,2,1
4,9
8
Maximum value of the sum of integers passing according to the rule on one line.
64

Flowchart:

Flowchart: Restore the original string by entering the compressed string with this rule.

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program to cut out words of 3 to 6 characters length from a given sentence not more than 1024 characters.
Next: Write a Java program to find the number of combinations that satisfy p + q + r + s = n where n is a given number <= 4000 and p, q, r, s in the range of 0 to 1000.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.