Hercy wants to save money for his first car. He puts money in the Leetcode bank every day.
He starts by putting in $1 on Monday, the first day. Every day from Tuesday to Sunday, he will put in $1 more than the day before. On every subsequent Monday, he will put in $1 more than the previous Monday.
Given n, return the total amount of money he will have in the Leetcode bank at the end of the nth day.
Example 1:
Input: n = 4 Output: 10 Explanation: After the 4th day, the total is 1 + 2 + 3 + 4 = 10.
Example 2:
Input: n = 10 Output: 37 Explanation: After the 10th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice that on the 2nd Monday, Hercy only puts in $2.
Example 3:
Input: n = 20 Output: 96 Explanation: After the 20th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96.
Constraints:
1 <= n <= 1000The iterative approach involves simulating each day in a loop, tracking both the weeks and individual days. We'll add the appropriate amount of money for each day based on the rules provided. This approach leverages basic looping constructs and conditionally increments the sums based on the day of the week.
This C solution uses a for loop to iterate through each day until n. It calculates the current 'week' number and the 'day of the week' using modulo arithmetic. It adds the appropriate amount for that day to a running total.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), where n is the number of days. Each day is processed once.
Space Complexity: O(1), only a constant amount of space is used.
The mathematical approach seeks to minimize iterations by using formulae to directly compute sums based on weeks, leveraging arithmetic series properties. This method is typically more efficient and concise.
This solution calculates the contribution of complete weeks and the remaining days separately using arithmetic sum formulae. It computes the sum of weeks' contributions and adds the extra days with incremental daily increases.
C++
Java
Python
C#
JavaScript
Time Complexity: O(1).
Space Complexity: O(1).
| Approach | Complexity |
|---|---|
| Iterative Approach | Time Complexity: O(n), where n is the number of days. Each day is processed once. |
| Mathematical Approach | Time Complexity: O(1). |
Calculate Money in Leetcode Bank - Leetcode 1716 - Python • NeetCodeIO • 7,614 views views
Watch 9 more video solutions →Practice Calculate Money in Leetcode Bank with our built-in code editor and test cases.
Practice on FleetCode