【1672. The total assets of the richest customers】

Leetcode

1672. Total Assets of the Richest Clients

You are given m x na grid of integers accountswhere accounts[i][j]is the number of assets held by the i​​​​​​​​​​​​-th customer at the j-th bank. Returns the total amount of assets .

The total amount of assets of customers is the sum of the assets they hold in various banks. The wealthiest customer is the customer with the largest total assets.

Source: LeetCode
Link: https://leetcode.cn/problems/richest-customer-wealth
Example 1:

Input: accounts = [[1,2,3],[3,2,1]]
Output: 6
Explanation:
Total assets of the first customer = 1 + 2 + 3 = 6
Total assets of the second customer = 3 + 2 + 1 = 6
Both customers are the richest, and the total amount of assets is 6, so return 6.

Example 2:

Input: accounts = [[1,5],[7,3],[3,5]]
Output: 10
Explanation:
The total assets of the first customer = 6
The total assets of the second customer = 10
The third The total amount of assets of the first customer = 8
The second customer is the richest, the total amount of assets is 10

Example 3:

Input: accounts = [[2,8,7],[7,1,3],[1,9,5]]
Output: 17

hint:

m == accounts.length
n == accounts[i].length
1 <= m, n <= 50
1 <= accounts[i][j] <= 100

class Solution {
    
    
public:
    int maximumWealth(vector<vector<int>>& accounts) {
    
    
        int max_wealth = 0; // 初始化最富有客户的资产总量为0

        // 遍历所有客户
        for (int i = 0; i < accounts.size(); i++) {
    
    
            int current_wealth = 0; // 初始化当前客户的资产总量为0

            // 遍历当前客户在所有银行的资产
            for (int j = 0; j < accounts[i].size(); j++) {
    
    
                current_wealth += accounts[i][j]; // 累加当前客户的资产总量
            }

            // 如果当前客户的资产总量大于已知的最大值,更新最大值
            if (current_wealth > max_wealth) {
    
    
                max_wealth = current_wealth;
            }
        }

        return max_wealth; // 返回最富有客户的资产总量
    }
};

the code

This C++ code defines a Solutionclass named , which contains a maximumWealthmember function named . The purpose of this function is to calculate accountsthe total assets of the wealthiest customers in a given grid of integers. The code uses accumulatefunctions of the C++ standard library and range-based for loops to simplify the calculation process.

Here is a detailed explanation of this code:

class Solution {
    
    
public:
    int maximumWealth(vector<vector<int>>& accounts) {
    
    
        int maxWealth = INT_MIN; // 初始化最富有客户的资产总量为最小整数
        
        // 使用范围基于的for循环遍历所有客户的账户(account)
        for (auto &account : accounts) {
    
    
            // 使用accumulate函数计算当前客户的资产总量,并与已知的最大值进行比较,取较大者
            maxWealth = max(maxWealth, accumulate(account.begin(), account.end(), 0));
        }
        
        return maxWealth; // 返回最富有客户的资产总量
    }
};

Complexity Analysis

  • Time complexity: O(mn), where m and nare the number of rows and columns accounts*accountsof .

  • Space Complexity: O(1).

In this solution, a range-based for loop is used to iterate through all customer accounts. accumulateThe function is taken from the C++ <numeric>header file and it takes three arguments: an iterator range (here sum account.begin()) account.end()and an initial value (here 0 ). accumulateThe function will calculate the sum of all elements within the range of the iterator.

By comparing the current client's total assets to the known maximum, we can update the wealthiest clients' total assets in real time. After the loop ends, maxWealththe variable will contain the wealthiest customer's total assets.

explain

  1. INT_MIN: INT_MINis a <climits>constant defined in the header file that represents intthe smallest negative integer that the type can represent. In most implementations, its value is -2147483648. In this code, maxWealthis initialized INT_MINto ensure that any asset totals encountered during traversal are larger than the initial value.
  2. for (auto &account : accounts): This is a range based for loop that iterates over accountseach element in the vector. autoThe keyword means to let the compiler automatically infer the type, &which means a reference. Thus, accountis accountsa reference to each vector element in . This loop syntax can simplify code and improve code readability.
  3. maxWealth = max(maxWealth, accumulate(account.begin(), account.end(), 0));
    • max()<algorithm>A function is a function defined in a C++ header file that takes two arguments and returns the larger one. In this example, it is used to compare the current maximum wealth value maxWealthwith the total assets of the current client.
    • accumulate()Function from the C++ <numeric>header file to compute the cumulative sum of elements in a given range. In this example, it calculates accountthe total assets of the current customer ( ). It takes three arguments: an iterator representing the start of the range ( account.begin()), an iterator representing the end of the range ( account.end()), and the initial value to accumulate (in this case 0).
    • By comparing accumulate()the result of the function with the current maxWealthone and taking the larger one, we can update the total assets of the wealthiest customers in real time.

range based for loop

范围基于的for循环( Range-based for loop) is C++11a new for loop syntax introduced for traversing elements in containers (such as arrays, vectors, etc.) more concisely and readably. Range-based for loops can automatically iterate over all elements of a container, avoiding the need to manually set iterators or index variables.

  • The general syntax of a range-based for loop is as follows:
for (declaration : range_expression) {
    
    
    // 循环体
}

  1. declaration: Declare a variable that will hold the current element in the container each time through the loop. Keywords are usually used autoto let the compiler infer the type automatically.
  2. range_expression: Indicates the container to be traversed (such as an array, vector, etc.).
  • A specific usage of a range-based for loop is as follows:
for (auto &x : container) {
    
    
    // 循环体
}
/*这是一种特定情况下的范围基于for循环语法,其中:

- `auto`关键字让编译器自动推断变量类型。
- `&`表示引用,这样在循环体内对`x`的修改会影响到容器中的实际元素。
- `x`是在每次循环中保存容器中当前元素的变量。
- `container`表示要遍历的容器(如数组、向量等)。
*/
  • Here is a simple example of a range based for loop:
#include <iostream>
#include <vector>

int main() {
    
    
    std::vector<int> numbers = {
    
    1, 2, 3, 4, 5};

    // 使用范围基于的for循环遍历向量中的元素
    for (auto number : numbers) {
    
    
        std::cout << number << " ";
    }

    return 0;
}

output:1 2 3 4 5

In this example, the range-based for loop iterates numbersover all the elements in the vector and assigns each element to numbera variable. Then in the loop body, we can use numberthe variable directly. This loop syntax is more concise than the traditional for loop, improving the readability of the code.

Guess you like

Origin blog.csdn.net/u013454780/article/details/130497304