All questions
MediumArrays · Matrix Traversal
Maximum Valid Matrix Expression
Written by a community member · · 2 attempts · 0% pass
1
Given a rectangular 2D matrix whose cells are strings containing either a single digit ("0" through "9"), "+", or "-", return the maximum value of any valid expression that can be read contiguously from left to right within one row or from top to bottom within one column.
A valid expression:
- starts with a digit;
- alternates strictly between a digit and an operator (
+or-), so it never contains consecutive digits or consecutive operators; and - may start and end at any cells along the chosen row or column. A single digit is therefore a valid expression.
Evaluate expressions from left to right using ordinary addition and subtraction. You may not change direction or skip cells. Return the maximum integer value.
Examples:
- In
[["9", "+", "3", "6"], ["+", "7", "-", "2"]],"9+36"is invalid because"3"and"6"are consecutive digits, while"9+3"is valid. - For
[["9", "+", "3", "6", "-"], ["+", "7", "-", "2", "-"], ["9", "+", "1", "-", "3"]], the maximum is18, obtained from the top-to-bottom expression9+9in column 0.
Constraints: the matrix is non-empty and rectangular, has at most 100 rows and 100 columns, and every cell is one of the three permitted forms.