LeetCode 1672. Richest Customer Wealth Java Solution
Problem
Richest Customer Wealth - LeetCode
Approach
This problem involves working with a 2D array to calculate the sum of values and optimize based on it.
Initially, I straightforwardly stored the sum of all values in an array and then found the maximum value by iterating through that array. However, with better optimization, it's possible to directly find the maximum value without needing to store values in an array.
Algorithm:
In the first loop, iterate through each array.
In the second loop, calculate the sum of values in each array.
After the second loop, compare the sum of values with the current maximum and update it if the sum is higher.
Return the stored maximum value.
Github Link
https://github.com/eunhanlee/LeetCode_1672_RichestCustomerWealth_Solution.git
Time Complexity: O(n), Space Complexity: O(1)
public class Solution {
/**
* Calculates the maximum wealth among customers.
*
* @param accounts 2D array representing customers and their account wealth
* @return Maximum wealth among customers
*/
public int maximumWealth(int[][] accounts) {
int max = 0; // Initialize the maximum wealth as 0.
for (int[] listOfWealth : accounts) {
int tempSum = 0; // Initialize temporary sum for each customer.
for (int wealth : listOfWealth) {
tempSum += wealth; // Add each account's wealth to the temporary sum.
}
max = Math.max(max, tempSum); // Update the maximum wealth if the temporary sum is greater.
}
return max;
}
}