Write a program that reads as a command-line argument a number n, this number is the number of columns and rows mentioned above. It then reads from standard input n*n integers, each integer being between zero (0) and one hundred (100), and then writes to standard out a single integer representing the maximum possible profit An example of a proper running of your program would like this: cd472$ javac Submission.java cd472$ java Submission 3 < digger3_input 191
HI, I have written the code, but I get the wrong inputs over and over. I have attached the question as an image, please can anyone help?
Thank you.
//<My_Code>
import java.util.Scanner;
public class Submission {
public static void main(String[] args){
//Input of the number of rows & columns
//Creating a grid to map out the recourses
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int[][] grid = new int[n][n];
for(int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
grid[i][j] = input.nextInt();
}
}
//2D integer arrays of max[num][value] collects from position
//'num' and 'value'
int[][] max = new int[n][n];
for(int j = 0; j < n; j++)
{
max[n -1][j] = grid[n - 1][j];
}
for(int i = n - 2; i >= 0; i--)
{
/***
* Inside the for-loop we insert an if statement to see
* whether they can move downwards towards right and left.
*
* Inside the two 'Else-if' we see whether they it can move only left,
* or only right respectively
*/
for(int j = 0; j < n; j++)
{
if(j - 1 >=0 && j + 1 < n)
{
max[i][j] = Math.max(max[i + 1][j + 1], max[i + 1][j - 1]) + grid[i][j];
}
else if (j - 1 >= 0 && j + 1 >= n)
{
max[i][j] = max[i + 1][j - 1] + grid[i][j];
}
else
{
max[i][j] = max[i + 1][j + 1] + grid[i][j];
}
}
}
/**
* Output of the result after comparing to each points in the first row
*/
int result = 0;
for(int j = 0; j < n; j++)
{
result = Math.max(result, max[0][j]);
}
System.out.println(result);
}
}
Trending now
This is a popular solution!
Step by step
Solved in 2 steps with 4 images