Python 1716.py
class Solution:
def totalMoney(self, n: int) -> int:
# it's too early in the morning to figure out the smart modulo math with triangle numbers,
# let's just brute force it :-)
result = 0
add = 0
for i in range(n):
add += 1
result += add
if i % 7 == 6: # Sunday
add -= 6
return result
Difficulty
and has an acceptance rate of about 82% (300k+ submissions).
Typical patterns to solve this problem:
- Math
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided Solution class implements a method totalMoney that computes the cumulative amount of money received over n consecutive days following a specific weekly pattern. The algorithm iterates day by day, incrementally building the total while resetting the daily increment after each Sunday. The implementation relies on a simple loop and a few integer variables, resulting in a clear and direct translation of the problem statement into code.
Key Steps
Initialization
result = 0
add = 0
Two accumulator variables are created before the loop begins. result holds the running sum of money, while add represents the amount added on the current day. Both start at zero, establishing a clean baseline for the subsequent calculations.
Daily Iteration
for i in range(n):
add += 1
result += add
if i % 7 == 6: # Sunday
add -= 6
The loop runs exactly n times, with i ranging from 0 to n-1. Inside each iteration, add is increased by one, reflecting the rule that each successive day contributes one more unit than the previous day. The updated add value is then added to result, accumulating the total money earned so far.
The conditional if i % 7 == 6 detects the seventh day of each week (Sunday) by checking the remainder of i divided by 7. When a Sunday is reached, add is decreased by six. This operation effectively resets the daily increment to the value that would be appropriate for the following Monday, because the next iteration will again add one to add. The net effect mirrors the pattern where each new week starts with a lower base amount.
Return Value
return result
After processing all n days, the method returns the accumulated total stored in result.
Edge Cases Handled
When n is zero, the range(n) construct yields an empty sequence, so the loop body never executes. Both result and add remain at their initial value of zero, and the method correctly returns 0. This behavior gracefully handles the lower bound of the input domain without requiring special-case code.
If n falls exactly on a Sunday boundary (for example, n = 7, 14, 21, …), the loop processes the final day as a Sunday, applies the decrement add -= 6, and then exits. The decrement does not affect the final result because it occurs after the day's contribution has already been added to result. Consequently, the method yields the correct total for any n that ends on a week boundary.
The modulo operation i % 7 works uniformly for any non-negative integer i, ensuring that the weekly reset logic remains valid regardless of how many weeks are traversed. This eliminates the need for separate handling of partial weeks or multiple-week cycles.
Performance Optimizations Observed
The algorithm uses only two integer variables and a single loop that iterates exactly n times. By updating add in place and adding it directly to result, the code avoids the overhead of constructing intermediate data structures such as lists or arrays. The modulo check i % 7 == 6 is a constant-time arithmetic operation, and its placement inside the loop incurs minimal cost because it is evaluated only once per iteration.
Because the loop body consists solely of arithmetic operations and a simple conditional, the interpreter can execute it with a tight instruction pipeline, leading to efficient use of CPU caches. The absence of function calls or recursion further reduces call-stack overhead, allowing the method to scale linearly with the input size while maintaining a low constant factor.
Overall, the implementation achieves a straightforward, low-overhead solution that directly maps the problem's weekly progression onto a linear scan, delivering fast execution for any permissible value of n.
ELI5 - Simplified Explanation
Imagine a little piggy bank where you put some coins in every single day. This code is like a helper who keeps track of how much money goes inside. On Monday, you put one coin in. On Tuesday, you put two coins in. Each day that follows, you always add one more coin than you did the day before.
When Sunday arrives, it is time for a fresh start. Instead of adding a giant pile of coins, the helper looks at how many days have passed. If you just finished a full week on Sunday, the helper resets the count so that the next Monday starts with just one extra coin more than the Monday before. The computer loops through every day from the first day until the day you pick, counting up all the coins as it goes along. It keeps doing this until it reaches the total number of days chosen.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||||
| WalkCCC | C++ | Python | Java | |||||||
| leetcode.ca | C++ | Python | Java | Go | TS | |||||
| Progiez | C++ | Python | Java | |||||||
| github | black-shadows | C++ | ||||||||
| charles-wangkai | Java | |||||||||
| DimitrisJim | C | |||||||||
| everthis | JS | |||||||||
| fartem | Ruby | |||||||||
| fsq | C++ | |||||||||
| halfrost | Go | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JS | |||||||||
| lkwq007 | Python | |||||||||
| pruthvikp | Python | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| withaarzoo | C++ | |||||||||
| YuriSpiridonov | Python | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | |||||||||
| Progiez | C++, Java, Python | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| DimitrisJim | C | |||||||||
| everthis | JavaScript | |||||||||
| fartem | Ruby | |||||||||
| fsq | C++ | |||||||||
| halfrost | Go | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JavaScript | |||||||||
| lkwq007 | Python | |||||||||
| pruthvikp | Python | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| withaarzoo | C++ | |||||||||
| YuriSpiridonov | Python |
Videos
Similar Problems
- problem 2591: Distribute Money to Maximum Children
Solved On The Same Day
- problem 1360: Number of Days Between Two Dates
- problem 1576: Replace All ?'s to Avoid Consecutive Repeating Characters
- problem 2409: Count Days Spent Together
- problem 2515: Shortest Distance to Target String in a Circular Array
- problem 2644: Find the Maximum Divisibility Score
- problem 1110: Delete Nodes And Return Forest
- problem 1296: Divide Array in Sets of K Consecutive Numbers
- problem 1443: Minimum Time to Collect All Apples in a Tree
- problem 1669: Merge In Between Linked Lists
- problem 458: Poor Pigs
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality