Sponsored
Sponsored
This approach involves iterating over each customer's accounts, calculating their total wealth by summing up the amounts, and keeping track of the maximum wealth found during these calculations. This method is simple and direct, leveraging basic iteration and comparison.
Time Complexity: O(m * n), where m is the number of customers and n is the number of banks.
Space Complexity: O(1), as we only use a few extra variables irrespective of input size.
1public class RichestCustomerWealth {
2 public int maximumWealth(int[][] accounts) {
3 int maxWealth = 0;
4 for (int[] customer : accounts) {
5 int currentWealth = 0;
6 for (int money : customer) {
7 currentWealth += money;
8 }
9 maxWealth = Math.max(maxWealth, currentWealth);
10 }
11 return maxWealth;
12 }
13
14 public static void main(String[] args) {
15 RichestCustomerWealth solver = new RichestCustomerWealth();
16 int[][] accounts = {{2,8,7},{7,1,3},{1,9,5}};
17 System.out.println(solver.maximumWealth(accounts));
18 }
19}
This Java solution involves iterating over the accounts
array to calculate the wealth of each customer and track the largest wealth using Math.max
.
This approach considers a more functional programming style by mapping over the initial list to compute each customer's wealth, thereby generating an array of wealth values, which is in turn reduced (or simply searched) to obtain the maximum wealth.
Time Complexity: O(m * n)
Space Complexity: O(m)
1def maximumWealth(accounts):
2
Here, map
is used to apply the sum
function across all customers in accounts, and then max
finds the highest resulting sum.