Richest Customer Wealth
Problem
Given an m×n matrix accounts where accounts[i][j] is customer i's balance in bank j, return the maximum total wealth across customers.
accounts = [[1,2,3],[3,2,1]]6def maximum_wealth(accounts):
return max(sum(row) for row in accounts)
function maximumWealth(accounts) {
return Math.max(...accounts.map(row => row.reduce((a, b) => a + b, 0)));
}
class Solution {
public int maximumWealth(int[][] accounts) {
int best = 0;
for (int[] row : accounts) {
int s = 0;
for (int x : row) s += x;
best = Math.max(best, s);
}
return best;
}
}
int maximumWealth(vector<vector<int>>& accounts) {
int best = 0;
for (auto& row : accounts) {
int s = 0;
for (int x : row) s += x;
best = max(best, s);
}
return best;
}
Explanation
Each customer is one row of the matrix, and that customer's total wealth is just the sum of their row. The richest customer is whoever has the biggest row sum, so the whole problem is "add up each row and keep the largest total."
The Python solution says exactly that: max(sum(row) for row in accounts). It computes sum(row) for every row and then takes the maximum of all those sums.
There is no need to sort or do anything fancy — we look at every cell once to build the row sums, and tracking the maximum is free as we go.
Example: accounts = [[1,2,3],[3,2,1]]. The first row sums to 6, the second also sums to 6. The maximum is 6, so the answer is 6.
Because we visit each of the m·n balances a single time, the running time is linear in the size of the matrix.