Problem 1672

Abstract / Summary

Find the maximum total wealth among all customers by summing the wealth of each customer and taking the highest sum.

Note

The full problem description, including helpful examples, can be found on LeetCode.

C++ 1672.cpp

class Solution {
public:
    int maximumWealth(vector<vector<int>>& accounts) {
        int maxcust = 0;
        int maxmoney = 0;
        for (int cust = 0; cust < accounts.size(); cust++)
        {
            int money = 0;
            for (auto m : accounts[cust])
                money += m;
            if (money < maxmoney)
                continue;

            maxmoney = money;
            maxcust = cust;
        }
        return maxmoney;
    }
};
19 lines | 479 bytes | submitted August 7, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 89% (1+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Matrix
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a Solution class with a single public method maximumWealth. The method receives a two-dimensional vector accounts, where each inner vector represents the balances of a single customer across multiple banks. The goal of the function is to compute the greatest total wealth among all customers and return that value.

The algorithm iterates through each customer, accumulates the sum of their account balances, and keeps track of the highest sum encountered. The final result is the maximum wealth found.

Key Steps

The core of the algorithm consists of three distinct actions: initialization, per-customer aggregation, and maximum-value update.

Initialization

int maxcust = 0;
int maxmoney = 0;

Two integer variables are created before the loops begin. maxcust stores the index of the customer with the highest wealth, while maxmoney holds the corresponding wealth amount. Both start at zero, which correctly represents the situation where no customers have been processed yet.

Per-customer aggregation

for (int cust = 0; cust < accounts.size(); cust++)
{
    int money = 0;
    for (auto m : accounts[cust])
        money += m;
    // ...
}

The outer for loop walks through each customer index cust. Inside the loop, a local accumulator money is reset to zero. The inner range-based for loop iterates over every balance m belonging to the current customer and adds it to money. This produces the total wealth for that customer.

Maximum-value update

if (money < maxmoney)
    continue;

maxmoney = money;
maxcust = cust;

After the total for a customer is computed, the code compares it with the current maximum. If the new total money is less than maxmoney, the continue statement skips the update, leaving the existing maximum unchanged. When money is greater than or equal to maxmoney, the algorithm assigns money to maxmoney and records the current index in maxcust. The final return maxmoney; delivers the highest wealth found.

Edge Cases Handled

The function gracefully handles several boundary conditions without additional checks:

When the input accounts is empty, accounts.size() evaluates to zero, causing the outer loop to execute zero times. The variables maxmoney and maxcust remain at their initial zero values, and the function returns zero, which correctly represents the maximum wealth in an empty dataset.

If a customer has no bank accounts, the inner vector is empty. The range-based loop over accounts[cust] performs no iterations, leaving money at zero. The comparison logic then treats this as a candidate wealth value, ensuring that customers with empty account lists are considered in the maximum calculation.

When multiple customers share the same highest wealth, the condition money < maxmoney prevents an update only when the new total is strictly less. Equality (money == maxmoney) triggers the update, resulting in maxcust being set to the later customer's index. Although the returned wealth remains the same, the algorithm consistently records the last occurrence of the maximum value.

All arithmetic operations use the int type, and the accumulation money += m works correctly for non-negative balances, which is the typical domain for account values.

Performance Considerations

The implementation processes each balance exactly once. The outer loop iterates over the number of customers, and the inner loop iterates over the number of banks for each customer. By accumulating the sum in a simple integer variable and performing a direct comparison, the code avoids any auxiliary data structures or repeated passes over the data.

The early-exit continue statement eliminates the assignment statements for customers whose wealth does not exceed the current maximum. This small shortcut reduces the number of write operations to maxmoney and maxcust, which can be beneficial when the dataset contains many customers with lower wealth than the current leader.

Because the algorithm uses only primitive integer variables and straightforward loops, it benefits from good cache locality. The inner loop accesses the balances of a single customer sequentially, which aligns with typical memory layout of vector<vector<int>> and minimizes cache misses.

Overall, the design achieves a single linear pass over the input data, delivering the required result efficiently.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a big row of piggy banks belonging to different people. Each person has a few smaller bags of coins inside their own special box. The goal is to find out who has the most coins in total. The code starts with two empty baskets. The first area keeps track of who is currently holding the most treasure, and the second area remembers how much that treasure is worth. A helper looks at each person one by one. For every person, the helper opens all their small bags and adds up every single coin to see the grand total. If this person has more coins than anyone seen so far, the helper remembers this new total as the biggest amount. This keeps happening until every person has been checked. At the very end, the amount in the basket that holds the biggest number is shared.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.81 | σ = 1.33

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go C PHP Rust TS
Progiez C++ Python Java
github black-shadows C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JS
fartem Ruby
fsq C++
halfrost Go
JoshCrozier JS
Krazune C++
lkwq007 Python
muhammadfarhankt Go
suxrobGM C#
varunu28 Java
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C, C++, Go, Java, PHP, Python, Rust, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fartem Ruby
fsq C++
halfrost Go
JoshCrozier JavaScript
Krazune C++
lkwq007 Python
muhammadfarhankt Go
suxrobGM C#
varunu28 Java
YuriSpiridonov Python
33 links | 19 authors | 11 languages

Videos

9 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

39 easy 31 medium 1 hard
72 solutions   August 7, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality