Problem 1716

Abstract / Summary

A bank deposits increasing amounts of money each day and pays interest; calculate the total after a set number of days.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
13 lines | 408 bytes | submitted December 6, 2023 | GitHub   30% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 82% (300k+ submissions).

Typical patterns to solve this problem:
  • Math
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 6 | μ = 5.96 | σ = 1.45

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
31 links | 20 authors | 9 languages

Videos

3 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

11 solutions   December 6, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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