algoadvance

Leetcode 1716. Calculate Money in Leetcode Bank

Problem Statement

You are given a bank account where you deposit money every day. The rules for the deposits are as follows:

Given n, the number of days, return the total money in the bank at the end of the nth day.

Clarifying Questions

  1. Q: Are the deposits reset to 1 dollar after every 7 days? A: Yes, the deposit resets every week.

  2. Q: Is n guaranteed to be a positive integer? A: Yes, n is a positive integer.

Strategy

  1. Initialize a variable totalMoney to keep track of the total amount of money.
  2. Use a loop to iterate from day 1 to day n:
    • For each day, calculate the week number and the day of the week.
    • Determine the deposit amount using the formula: week number + day of the week.
    • Add the deposit amount to totalMoney.
  3. Return the totalMoney.

Code

Here is the Java implementation of the strategy:

public class CalculateMoneyInBank {
    public int totalMoney(int n) {
        int totalMoney = 0; // Initialize total amount of money
        for (int day = 1; day <= n; day++) {
            int week = (day - 1) / 7; // Determine the week number
            int dayOfWeek = (day - 1) % 7; // Determine the day of the week
            totalMoney += week + dayOfWeek + 1; // Calculate deposit for the day
        }
        return totalMoney;
    }

    public static void main(String[] args) {
        CalculateMoneyInBank bank = new CalculateMoneyInBank();
        System.out.println(bank.totalMoney(10)); // Example test case
    }
}

Explanation

  1. Loop through each day: The loop runs from 1 to n (inclusive) where day is the current day.
  2. Calculate week number and day of the week:
    • week = (day - 1) / 7: This gives the zero-based week number (0 for the first week, 1 for the second week, etc.).
    • dayOfWeek = (day - 1) % 7: This gives the zero-based day of the week (0 for Monday, 6 for Sunday).
  3. Calculate the deposit amount:
    • The deposit for each day can be found using the formula week + dayOfWeek + 1.
  4. Accumulate the total money:
    • Add the calculated deposit to totalMoney.

Time Complexity

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI