Richest Customer Wealth
You are given an m x n integer grid accounts where accountsi[j] is the amount of money the i-th customer has in the j-th bank. Return the wealth that the richest customer has, where a customer wealth is the sum of all their bank accounts . Sum each row, then track the maximum row sum seen so far as you go.
Constraints
- m == accounts.length
- n == accountsi.length
- 1 ≤ m, n ≤ 50
- 1 ≤ accountsi[j] ≤ 100
Example
accounts = [[1, 2, 3], [3, 2, 1]]6Explanation Customer 0 has 1+2+3=6, customer 1 has 3+2+1=6, so the richest wealth is 6.
Sum each customer row, track the largest total
Customer 0: [1, 2, 3] sums to 6. maxWealth=6.
What happens in this step
row 0 = [1, 2, 3] sum = 1 + 2 + 3 = 6 maxWealth = 6
Steps to visualize
- For each customer (each row), add up every bank balance in that row.
- Compare that row sum against the largest sum found so far.
- Keep the larger of the two as the new maximum.
- After checking every customer, the maximum is the richest wealth.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
Customer 0: [1, 2, 3] sums to 6. maxWealth=6.
What happens in this step
row 0 = [1, 2, 3] sum = 1 + 2 + 3 = 6 maxWealth = 6
Solution
function maximumWealth(accounts) {
let maxWealth = 0;
for (const row of accounts) {
let sum = 0;
for (const balance of row) {
sum += balance;
}
maxWealth = Math.max(maxWealth, sum);
}
return maxWealth;
}- Time
- O(m * n)
- Space
- O(1)
Test cases
| Input | Expected | Covers |
|---|---|---|
accounts = [[1, 2, 3], [3, 2, 1]] | 6 | example from the docstring |
accounts = [[1, 5], [7, 3], [3, 5]] | 10 | one customer clearly richer than the others |
accounts = [[2, 8, 7]] | 17 | smallest valid input, a single customer |
accounts = [[5], [10], [3]] | 10 | each customer has only one bank account |
accounts = [[4, 4], [4, 4]] | 8 | every customer has identical wealth |
accounts = [[100]] | 100 | smallest possible grid, one customer with one bank |