The “Richest Customer Wealth” problem involves finding the maximum wealth among a group of customers, where each customer has a certain amount of wealth represented by an array of arrays. Each inner array represents a customer, and the elements of these arrays represent the amounts of money in different accounts.
Problem Statement
Given a 2D array where each element is a customer’s account balances, find the maximum wealth among all customers.
Example
For the input:
[[1, 2, 3],
[3, 2, 1],
[2, 3, 1]]
The wealth of each customer is:
- Customer 1: 1 + 2 + 3 = 6
- Customer 2: 3 + 2 + 1 = 6
- Customer 3: 2 + 3 + 1 = 6
The output should be 6, as all customers have the same wealth.
C# Implementation
Here’s how you can implement this in C#:
using System;
public class RichestCustomer
{
public static int MaximumWealth(int[][] accounts)
{
int maxWealth = 0;
foreach (var customerAccounts in accounts)
{
int currentWealth = 0;
foreach (var account in customerAccounts)
{
currentWealth += account;
}
if (currentWealth > maxWealth)
{
maxWealth = currentWealth;
}
}
return maxWealth;
}
public static void Main(string[] args)
{
int[][] accounts = new int[][]
{
new int[] { 1, 2, 3 },
new int[] { 3, 2, 1 },
new int[] { 2, 3, 1 }
};
int richestWealth = MaximumWealth(accounts);
Console.WriteLine($"The richest customer's wealth is: {richestWealth}");
}
}
Explanation
-
Data Structure:
- The accounts are represented as a 2D array (or jagged array in C#), where each inner array represents a customer’s accounts.
-
MaximumWealth Method:
- This method iterates through each customer’s accounts to calculate their total wealth.
- It uses a variable
maxWealth
to keep track of the highest wealth encountered. - For each customer, a nested loop sums up the wealth in their accounts. If this sum is greater than the current
maxWealth
, it updatesmaxWealth
.
-
Main Method:
- It initializes a sample 2D array representing the account balances and calls the
MaximumWealth
method. - Finally, it prints the maximum wealth found.
- It initializes a sample 2D array representing the account balances and calls the
Complexity
- Time Complexity: O(m * n), where
m
is the number of customers andn
is the average number of accounts per customer. This is because we iterate through all accounts. - Space Complexity: O(1) for the space used in calculations, since we’re using a fixed number of variables regardless of input size.
Output
When you run the program, it will display:
The richest customer's wealth is: 6
This implementation is straightforward and effectively calculates the maximum wealth among customers based on their account balances.