LeetCode 1479: Sales by Day of the Week

Database

Problem Description

Explanation

To solve this problem, we need to calculate the sales for each day of the week based on the given sales data. The input consists of a list of sales for each day of the month, and we need to calculate the total sales for each day of the week (Sunday to Saturday) for the entire month.

We can achieve this by iterating over the sales data and accumulating the sales amount for each day of the week. To map the days of the week to their corresponding index (0 for Sunday, 1 for Monday, ..., 6 for Saturday), we can use a mapping array or a simple formula.

Algorithm

  1. Initialize an array weekSales of size 7 to store the total sales for each day of the week.
  2. Iterate over the given sales array and for each day:
    • Calculate the day of the week using the formula (startDay + i - 1) % 7, where startDay is the index of the start day of the month and i is the day index.
    • Accumulate the sales amount for that day of the week in weekSales.
  3. Return the weekSales array containing the total sales for each day of the week.

Time Complexity

The time complexity of this algorithm is O(N), where N is the number of days in the sales data.

Space Complexity

The space complexity of this algorithm is O(1) as we only use a fixed-size array to store the total sales for each day of the week.

Solutions

class Solution {
    public int[] salesByDayOfWeek(int[] sales, int startDay) {
        int[] weekSales = new int[7];
        
        for (int i = 0; i < sales.length; i++) {
            int dayOfWeek = (startDay + i - 1) % 7;
            weekSales[dayOfWeek] += sales[i];
        }
        
        return weekSales;
    }
}

Loading editor...