[Leet Code] Calculate Money in Leetcode Bank
Leetcode: https://leetcode.com/problems/calculate-money-in-leetcode-bank/
Problem:
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.
Solution:
class Solution(object):
def totalMoney(self, n):
"""
:type n: int
:rtype: int
"""
counter = 1
acc = 0
value = 1
starting_value = 1
while counter != n+1:
if counter % 7==0:
acc+=value
counter+=1
starting_value+=1
value=starting_value
else:
acc+=value
value+=1
counter+=1
return acc
Explanation:
First we initalise the variables that we’re going to be using, counter, accumulator (acc), value, and starting_value. Value is the amount to add on each day, this will continue to increment. The starting value is what will get incremented at the start of a new week, and will be assigned to the value variable. Then we do a while loop, while counter is not equal to n+1, first we check if counter is a divisor of 7, if so, we add the current value to the accumulator variable, then we increment the counter, as well as the starting_value, and finally, we assign the value of starting_value to value. Otherwise, if it’s not a divisor of 7, we add the value of value to the accumulator, add 1 to the value, and increment the counter by 1 too. Then when this loop breaks, i.e. the counter == n+1, we return the accumulator variable.