Make writing a habit together! This is the 14th day of my participation in the “Gold Digging Day New Plan · April More Text Challenge”. Click here for more details

More and more testing positions, in addition to basic functional testing, programming background, scripting experience to stand out.

How can we improve our programming ability, brush LeetCode is one of the best way, not most of the words, brush the topic to go ~

I. Title Description:

  • The subject content

  • The subject sample

  • title

    • This gives you a two-dimensional array accounts argument.
    • Accounts, accounts[I] of length [1,51]
    • Accounts [I][j] element is int and ranges from [1,101]

Ii. Analysis of Ideas:

We have our problem, which gives us a two-dimensional array accounts, and asks us to find the elements in Accounts [I] and the largest.

After looking at the example, we immediately have a method in mind to simulate the sum:

  • Use two for loops to iterate over the two-dimensional array accounts.
  • Level 1 for loop retrieves the list of elements in each row of the two-dimensional array accounts[I]
  • The second level for loop fetches each element from accounts[I][j]
  • Sum the elements in account[I] using a temporary variable Sum
  • The Sum of each time is compared with ANS, which takes the maximum value each time
  • Until all the elements of accounts are iterated, return ANS

With this in mind, we can quickly implement the problem by using two for loops as follows:

ans = 0
for i in range(len(accounts)):
    
    Sum = 0
    for j in range(len(accounts[i])):

        Sum = Sum + accounts[i][j]
        ans = max(ans,Sum)
return ans
Copy the code

Two for loops will do the trick, but they’re very slow. So is there another way?

  • We can optimize the above method by using only one for loop
  • A for loop retrieves the element of accounts, that is, account[I]
  • Sums over accounts[I] directly using the summation function sum()
  • The temporary variable ANS compares with the maximum value of sum(Account [I])
  • Change the array accounts until the loop is complete, returning ans
ans = 0

for i in accounts:
            
    ans = max(ans,sum(i))

return ans
Copy the code

And finally, this is a problem that we could have solved with just one line of code

  • The derived type
return max(sum(i) for i in accounts)
Copy the code

Iii. Summary:

We just use a for loop, submit the code, and the AC records are as follows:

Time complexity O(N), length space complexity O(1) of the Accounts array

That’s the content of this episode, please give your thumbs up and comments. See you next time