Category: Easy
Problem
You are given an m x n
integer grid accounts
where accounts[i][j]
is the amount of money the ith
customer has in the jth
bank. Return the wealth that the richest customer has.
A customer’s wealth is the amount of money they have in all their bank accounts. The richest customer is the customer that has the maximum wealth.
Examples
Example 1:
1 2 3 4 5 6 | Input: accounts = [[1,2,3],[3,2,1]] Output: 6 Explanation: 1st customer has wealth = 1 + 2 + 3 = 6 2nd customer has wealth = 3 + 2 + 1 = 6 Both customers are considered the richest with a wealth of 6 each, so return 6. |
Example 2:
1 2 3 4 5 6 7 | Input: accounts = [[1,5],[7,3],[3,5]] Output: 10 Explanation: 1st customer has wealth = 6 2nd customer has wealth = 10 3rd customer has wealth = 8 The 2nd customer is the richest with a wealth of 10. |
Constraints
m == accounts.length
n == accounts[i].length
1 <= m, n <= 50
1 <= accounts[i][j] <= 100
Solution Approach
In this problem of the richest customer wealth, We are given a 2D array. We have to find the array whose sum is greatest and need to return the sum as the answer.
The problem is pretty straightforward and by using brute force also we can get to the answer. We have to iterate through each row and find the sum of the numbers in that row. We also have to keep one variable to store the value of the maximum array row sum. The variable is updated every time it finds a row sum greater than itself.
Since the 2D grid is of size m*n and we iterate through it once, hence the time complexity is O(m*n). We are using one variable to store the maximum value and hence our space complexity is O(1).
Coming to the code of this approach, we first declare a variable to store the maximum value. This variable will be returned as the answer. We also have to declare a variable to store the sum of the row element values. Then we loop through the row using and inside that we loop through every element of the row. We keep adding the elements to the sum variable. At the end of the inner loop, we just check if that sum value is greater than the max value or not. If it is greater, then we change the max value to reflect that. We have to change the sum variable’s value to 0 for every outer loop iteration. In the end, we return the maximum value variable as the answer.
Solution code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class Solution { public int maximumWealth(int[][] accounts) { int maximum = 0; for (int i = 0; i < accounts.length; i++) { int sum = 0; for (int j = 0; j < accounts[i].length; j++) { sum += accounts[i][j]; } maximum = sum>maximum?sum:maximum; } return maximum; } } |
For more Leetcode explained solutions visit Leetcode Solutions.
If you like capture the flag challenges visit here.
Check out my socials below in the footer. Feel free to ask any doubts in the comment section or contact me via the Contact page I will surely respond. Happy Leetcoding 🙂