はじめに
LeetCodeの問題を解答します。
なるべく、問題の和訳と詳細なコメントを書いています。
余裕があれば、複数のアプローチの解答と、実際の面接を想定して英語での解法やコメントを書いています。
様々なカテゴリの問題をランダムにあたる方法も良いですが、
二分探索、連結リストなど、テーマを絞って集中的に解いた方が練習しやすい方は以下の記事が有用です。
テーマごとに問題を分類しました。
LeeetCodeの問題をアルゴリズムとデータ構造による分類しました。
また、LeetCodeではAtcoderと違ってクラスと関数を定義して解答します。
LeetCodeに特有の内容など、知っておくと役に立つかもしれないことをまとめています。
はじめてLeetCodeに触れる方はこちらの記事も役に立つと思います。
ポイント
- 二重配列を扱います。
この記事で得られること
- 二重配列の扱い
- 二重ループの方法
この記事が役立ちそうな方
- LeetCode初心者
- Python初心者
- 二重配列、二重ループの練習をしたい方
詳細
問題
原文
You are given an
m x n
integer gridaccounts
whereaccounts[i][j]
is the amount of money theith
customer has in thejth
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.
Example 1:
123456 Input: accounts = [[1,2,3],[3,2,1]]Output: 6Explanation:1st customer has wealth = 1 + 2 + 3 = 6</code><code>2nd customer has wealth = 3 + 2 + 1 = 6</code>Both customers are considered the richest with a wealth of 6 each, so return 6.Example 2:
1234567 Input: accounts = [[1,5],[7,3],[3,5]]Output: 10Explanation:1st customer has wealth = 62nd customer has wealth = 103rd customer has wealth = 8The 2nd customer is the richest with a wealth of 10.Example 3:
12 Input: accounts = [[2,8,7],[7,1,3],[1,9,5]]Output: 17
Constraints:
m == accounts.length
n == accounts[i].length
1 <= m, n <= 50
1 <= accounts[i][j] <= 100
内容(和訳)
m x nの整数配列accounts が与えられます。accounts[i][j]は、i番目の顧客がj番目の銀行に持っているお金の量です。一番裕福な顧客が持つ総額を返してください。
富の総額は、彼らが持っているすべての銀行口座のお金の量です。
※正しくない可能性があります。
解答
解答1:Python
1 2 3 4 5 6 7 8 9 10 |
class Solution: def maximumWealth(self, accounts: List[List[int]]) -> int: #富の最大値を保持する変数 richest_customer_wealth = 0 #accountsを一巡して走査 for i in range(len(accounts)): #各要素の合計値と、現在の富の最大値を比較して大きい方を記録 richest_customer_wealth = max(richest_customer_wealth, sum(accounts[i])) #富の最大値をを返す return richest_customer_wealth |
accountsの各要素の合計値の中で一番大きい値を返します。
max()を使うと、2つの要素の大きい方を取得できます。
min()もあります。
解答2:Python, 二重ループ
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class Solution: def maximumWealth(self, accounts: List[List[int]]) -> int: #富の最大値を保持する変数 richest_customer_wealth = 0 #accountsを一巡して走査 for i in range(len(accounts)): #accountsの各要素の合計を保持する変数 sum_of_account = 0 #accountsの各要素を一巡して走査 for j in accounts[i]: #合計値を加えていく sum_of_account += j #各要素の合計値と、現在の富の最大値を比較して大きい方を記録 richest_customer_wealth = max(richest_customer_wealth, sum_of_account) #富の最大値をを返す return richest_customer_wealth |
for文を二重にして、accountsの各要素の合計を1つずつ加えていく形にしました。
終わりに
補足・参考・感想
問題を分類しました。テーマごとに集中して問題を解くことができます。
LeeetCodeの問題をアルゴリズムとデータ構造による分類
LeetCodeに特有の内容など、知っておくと役に立つかもしれないことをまとめました。
疑問が解決した方は他の問題もどうぞ
コメント