LeetCode 1159: Market Analysis II Solution
Master LeetCode problem 1159 (Market Analysis II), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1159. Market Analysis II
Problem Explanation
Explanation
To solve this problem, we need to find the average daily price for each item in the market for each day. We can achieve this by iterating through the given data and keeping track of the cumulative sum and count of prices for each item. Then, we can calculate the average price for each item on each day and store the results in a new matrix for output.
Algorithm:
- Create a HashMap to store the cumulative sum and count of prices for each item.
- Iterate through the given data and update the HashMap with the cumulative sum and count for each item.
- For each day, calculate the average price for each item using the cumulative sum and count stored in the HashMap.
- Store the average prices in the output matrix.
Time complexity: O(n*m), where n is the number of days and m is the number of items. Space complexity: O(m), where m is the number of items.
Solution Code
class Solution {
public double[][] calculateItemAverage(int[][] prices) {
Map<Integer, double[]> map = new HashMap<>();
for (int[] price : prices) {
for (int i = 0; i < price.length; i++) {
if (!map.containsKey(i)) {
map.put(i, new double[]{0, 0});
}
map.get(i)[0] += price[i];
map.get(i)[1]++;
}
}
double[][] averages = new double[prices.length][prices[0].length];
for (int i = 0; i < prices.length; i++) {
for (int j = 0; j < prices[0].length; j++) {
averages[i][j] = map.get(j)[0] / map.get(j)[1];
}
}
return averages;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1159 (Market Analysis II)?
This page provides optimized solutions for LeetCode problem 1159 (Market Analysis II) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1159 (Market Analysis II)?
The time complexity for LeetCode 1159 (Market Analysis II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1159 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1159 in Java, C++, or Python.