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;
}
};
Difficulty
and has an acceptance rate of about 89% (1+ million submissions).
Typical patterns to solve this problem:
- Array
- Matrix
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
Other Solutions
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 |
Videos
Solved On The Same Day
- problem 13: Roman to Integer
- problem 21: Merge Two Sorted Lists
- problem 28: Find the Index of the First Occurrence in a String
- problem 35: Search Insert Position
- problem 58: Length of Last Word
- problem 66: Plus One
- problem 67: Add Binary
- problem 69: Sqrt(x)
- problem 70: Climbing Stairs
- problem 206: Reverse Linked List
- problem 242: Valid Anagram
- problem 278: First Bad Version
- problem 283: Move Zeroes
- problem 367: Valid Perfect Square
- problem 374: Guess Number Higher or Lower
- problem 389: Find the Difference
- problem 441: Arranging Coins
- problem 459: Repeated Substring Pattern
- problem 509: Fibonacci Number
- problem 657: Robot Return to Origin
- problem 682: Baseball Game
- problem 704: Binary Search
- problem 709: To Lower Case
- problem 744: Find Smallest Letter Greater Than Target
- problem 746: Min Cost Climbing Stairs
- problem 860: Lemonade Change
- problem 896: Monotonic Array
- problem 976: Largest Perimeter Triangle
- problem 1137: N-th Tribonacci Number
- problem 1232: Check If It Is a Straight Line
- problem 1275: Find Winner on a Tic Tac Toe Game
- problem 1351: Count Negative Numbers in a Sorted Matrix
- problem 1491: Average Salary Excluding the Minimum and Maximum Salary
- problem 1502: Can Make Arithmetic Progression From Sequence
- problem 1523: Count Odd Numbers in an Interval Range
- problem 1539: Kth Missing Positive Number
- problem 1572: Matrix Diagonal Sum
- problem 1768: Merge Strings Alternately
- problem 1822: Sign of the Product of an Array
- problem 2: Add Two Numbers
- problem 5: Longest Palindromic Substring
- problem 33: Search in Rotated Sorted Array
- problem 34: Find First and Last Position of Element in Sorted Array
- problem 43: Multiply Strings
- problem 50: Pow(x, n)
- problem 54: Spiral Matrix
- problem 62: Unique Paths
- problem 63: Unique Paths II
- problem 64: Minimum Path Sum
- problem 73: Set Matrix Zeroes
- problem 74: Search a 2D Matrix
- problem 120: Triangle
- problem 139: Word Break
- problem 153: Find Minimum in Rotated Sorted Array
- problem 198: House Robber
- problem 221: Maximal Square
- problem 275: H-Index II
- problem 279: Perfect Squares
- problem 300: Longest Increasing Subsequence
- problem 436: Find Right Interval
- problem 445: Add Two Numbers II
- problem 528: Random Pick with Weight
- problem 540: Single Element in a Sorted Array
- problem 611: Valid Triangle Number
- problem 658: Find K Closest Elements
- problem 852: Peak Index in a Mountain Array
- problem 981: Time Based Key-Value Store
- problem 1041: Robot Bounded In Circle
- problem 1146: Snapshot Array
- problem 2300: Successful Pairs of Spells and Potions
- problem 154: Find Minimum in Rotated Sorted Array II
Extra
- 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