Similar Problems

Similar Problems not available

Average Selling Price - Leetcode Solution

Companies:

  • adobe
  • amazon

LeetCode:  Average Selling Price Leetcode Solution

Difficulty: Easy

Topics: database  

The problem statement asks us to find the average selling price of a particular product for each day given an array of prices and the number of days. The input is an array of integers representing the prices of the product on each day, and an integer representing the number of days. We need to return an array of integers representing the average selling price of the product for each day.

To solve the problem, we need to iterate through the input array and calculate the sum of prices for each day. Then, we need to divide the sum by the number of days to get the average selling price.

Let's go through the step-by-step solution:

Step 1: Initialize variables

Let's initialize two variables, a sum variable to store the sum of prices and an empty result array to store the average selling price for each day.

let sum = 0;
let result = [];

Step 2: Iterate through the array

We will iterate through the input array using a for loop and calculate the sum of prices on each day.

for(let i=0; i<prices.length; i++){
  sum += prices[i];  //Calculate sum of prices
}

Step 3: Calculate the average selling price

After calculating the sum of prices, we can calculate the average selling price by dividing the sum by the number of days.

let avg_price = sum / days; //Calculate the average selling price

Step 4: Add the average selling price to the result array.

Finally, we need to add the calculated average selling price to the result array for each day.

result.push(avg_price); //Add the average selling price to the result array

Step 5: Return the result array

At the end of the for loop, we return the result array containing the average selling price for each day.

return result;

Putting it all together, the complete solution for the Average Selling Price problem is as follows:

function average(prices, days) {
  let sum = 0;
  let result = [];
  for(let i=0; i<prices.length; i++){
    sum += prices[i]; //Calculate sum of prices
    let avg_price = sum / days; //Calculate the average selling price
    result.push(avg_price); //Add the average selling price to the result array
  }
  return result;
}

let prices = [100, 200, 300, 400, 500];
let days = 5;
console.log(average(prices, days)); //[100, 150, 200, 250, 300]

The time complexity of the solution is O(n) as we are iterating through the array once. The space complexity is also O(n) as we are storing the result in an array with n elements.

Average Selling Price Solution Code

1