Working with Rows
Part of: 2D Array
Treating a Row as a Unit. Because a 2D array is an array of rows, you can process one entire row by fixing the row index r and looping only over the columns. This makes per-row statistics natural: row sums, row maximums, or finding which row has some property. Here the outer loop chooses a row and the inner loop sweeps that row's columns. The accumulator rowSum resets each time the outer loop advances, so each row is summed independently. Finding the Best Row. A common pattern is to compute a value for each row, then track which row scored highest: Key Points About Rows. - The outer loop variable is the row you are focused on; hold it constant while the inner loop varies the column. - A whole row is accessible as grid[r], a 1D array of length grid[r].length. - Per-row accumulators must be declared inside the outer loop so they reset for each row. What usually goes wrong. What you see What caused it How to fix it --- --- --- Row sums keep climbing as the traversal moves down the grid The accumulator was declared before the outer loop, so each row added onto the last Declare it inside the outer loop The answer is 0 on a grid where every value is negative The best so far was seeded wi
Challenge: Largest Row Sum