can you explain an algorithm used to solve this problem without coding it: You a
ID: 3734934 • Letter: C
Question
can you explain an algorithm used to solve this problem without coding it:
Explanation / Answer
Solution 1: Simple but not efficient: Use two loops-
Steps:
(1): Run a loop on given price array , from i=0 to n-1
(2) -----go inside the loop and declare count=0;
(3)-----Run another loop inside first loop,like while(j>=0 && price[j]<=price[i]) means from j=i-1 to 0
(4)---------increment count inside second loop
(5)----Now assigne value of count to spam[i]=count
Algorithm:
calculateSpan(int price[], int n, int spam[])
(1) for i<-0 to n-1 {
(2)count=0,j=i-1
(3)while(j>=0 and price[j]<=price[i]){
(4) count++
(5) }
(6) span[i]=count
(7) }
Analysis:
Time complexity: O(N*N) if N is length of prices array
Space Complexity: O(1), No extra array used
*****************************************************************************
Solution 2: Efficient using Stack. -
steps:
(1) declare empty stack , stack will store indexes of prices
(2) Traverse the price array
(3)----Remove elements from stack till price[stack[top]]<=price[i] or stack.empty() means remove till top of stack is smaller than current price
(4)----If stack is empty means all left element are smaller than current element
(5)--------span[i]=i
(6)----else
(7)--------span[i]=i-stack.top()
(8)---stack.push(i)
Algorithm: This algorithm using stack
//I wrote with brackets so you can understand it clearly
void calculateSpan(int prices[], int n, int span[])
{
// Creata a stack
stack
//push index of first element
stack.push(0);
// Span value of first element is always 0
span[0] = 0;
// Calculate span values for rest of the elements
for (int i = 1; i < n; i++)
{
// Pop elements from stack while stack is not empty and top of
// stack is smaller than price[i]
while (!stack.empty() && price[stack.top()] <= price[i])
{
stack.pop();
}
if(stack.isEmpty())
{
span[i]=i;
}
else
{
span[i]=i-stack.top();
}
// Push this element to stack
sttack.push(i);
}
}
Analysis:
Time complexity: O(N) if N is length of prices array
Space Complexity: O(N), Size of stack
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.