Question

In: Computer Science

I NEED AN NLOGN OR LINEAR SOLUTION TO THIS PROBLEM! I NEED A FASTER SOLUTION THAN...

I NEED AN NLOGN OR LINEAR SOLUTION TO THIS PROBLEM!

I NEED A FASTER SOLUTION THAN THE ONE GIVEN BELOW!! The solution below runs in quadratic time, I need one faster than this.

I REPEAT I NEED A FASTER SOLUTION!! THE SOLUTION GIVEN BELOW IS TOO SLOW!

Slow Solution:

def predictAnswer(stockData, queries):
    stockData = [0] + stockData
    length = len(stockData)
    ans = []
    for q in queries:
        l = q-1
        r = q+1
        flag = True
        while l > 0 or r < length:
            if l > 0 and stockData[l] < stockData[q]:
                ans.append(l)
                flag = False
                break
            if r < length and stockData[r] < stockData[q]:
                ans.append(r)
                flag = False
                break
            l -= 1
            r += 1
        if flag:
            ans.append(-1)
    return ans

Question:

The function predictAnswer should be made based on the following.

In the prediction game, the first player gives the second player some stock market data for some consecutive days. The data contains a company's stock price on each day. The rules for the game are:

  1. Player 1 will tell player 2 a day number
  2. Player 2 has to find the nearest day on which stock price is smaller than the given day
  3. If there are two results, then player 2 finds the day number which is smaller
  4. If no such day exits, then the answer is -1.

Example 1;

stockData size n =10;

stockData = [5,6,8,4,9,10,8,3,6,4]

queries = [6,5,4]

Result is [5,4,8]

On day 6, the stock price is 10. Both 9 and 8 are lower prices one day away. Choose 9 (day 5) because it is before day 6. On day 5, the stock price is 9. 4 is the closest lower price on day 4. On day 4, the stock price is 4. The only lower price is on day 8. The return array is [5,4,8]

Example - 2

stockData size n = 10

stockData = [5,6,8,4,9,10,8,3,6,4]

queries = [3,1,8]

Result is [2,4,-1]

If the day number is 3.both days 2 and 4 are smaller.choose the earlier day,day 2.

If the day number is 1,day 4 is the closet day with a smaller price.

If the day number is 8,there is no day where the price is less than 3.

The return array is [2,4,-1]

/*

     * Complete the 'predictAnswer' function below.

     *

     * The function is expected to return an INTEGER_ARRAY.

     * The function accepts following parameters:

     *  1. INTEGER_ARRAY stockData

     *  2. INTEGER_ARRAY queries

     */

def predictAnswer(stockData, queries):

Solutions

Expert Solution

We maintain two stacks, one for left side and the other for right side to calculate the answer.

Algorithm: 
Start from the first stock and do this for all the stocks
a) If stack is empty or stockData[i] is higher than the stockPrice at top of stack, then push ‘i’ to stack.
b) If this stockPrice is smaller than the top of stack, then keep removing the top of stack while top of the stack is greater.

Runtime complexity:

Space complexity:

import sys

def predictAnswer(stockData, queries):
    n = len(stockData)
    left = [0] * n
    right = [0] * n

    # Implementing stack using list
    stack = list()

    # Processing minimum stack for left side
    for i, stock in enumerate(stockData):
        while len(stack) != 0 and stock <= stockData[stack[-1]]:
            stack.pop()
        if len(stack) == 0:
            left[i] = -2
        else:
            left[i] = stack[-1]
        stack.append(i)

    # Re initializing stack
    stack = list()

    # Processing minimum stack from right side
    for i, stock in reversed(list(enumerate(stockData))):
        while len(stack) != 0 and stock <= stockData[stack[-1]]:
            stack.pop()
        if len(stack) == 0:
            right[i] = -2
        else:
            right[i] = stack[-1]
        stack.append(i)

    ans = [0] * len(queries)

    for i, query in enumerate(queries):
        ans[i] = -1
        diff = sys.maxsize
        if left[query - 1] != -2:
            ans[i] = left[query - 1] + 1
            diff = query - 1 - left[query - 1]
        if right[query-1] != -2 and diff > right[query - 1] - query + 1:
            ans[i] = right[query - 1] + 1
    return ans


# Driver code
if __name__ == "__main__":
    # stockData = [5, 6, 8, 4, 9, 10, 8, 3, 6, 4]
    # queries = [6, 5, 4]
    # stockData = [5, 6, 8, 4, 9, 10, 8, 3, 6, 4]
    # queries = [3, 1, 8]
    # stockData = [2, 4, 5, 1]
    # queries = [3]
    stockData = [1, 6, 5, 1]
    queries = [3]
    print(predictAnswer(stockData, queries))

Related Solutions

I need the calculation of this problem. This question has solution but I can't figure the...
I need the calculation of this problem. This question has solution but I can't figure the answer calculation Again I need calculation probably last line Question : On a certain standardized test The mean is 51 The standard deviation is 15 Exactly 66% of the people who took the test scored higher than Mr. Peterson. Find a, b, and c such that Mr. Peterson's score is approximately a + b ⋅ Φc(d) Do not make a continuity correction. What is...
Why is Gauss Elimination faster than solving a system of linear equations by using the inverse...
Why is Gauss Elimination faster than solving a system of linear equations by using the inverse of a Matrix? (I know it has something to do with there being less operation with Gauss elim.) Can you show an example with a 2x2 and 3x3 matrix?
Topic is Big O Problem 5 Invent a faster solution to the ThreeSum problem. Then determine...
Topic is Big O Problem 5 Invent a faster solution to the ThreeSum problem. Then determine the number of triples of integers that sum to zero in 8ints.txt. Hint 1:Sort the array first (use Java’s built-inArrays.sort(int[] a))method to sort the array first. Hint 2:A pair a[i] and a[j] is part of a triple that sums to zero if and only if the value-(a[i]+ a[j])is in the array (but not a[i] or a[j] ). ----------------- ThreeSum.java import java.util.Arrays; public class ThreeSum...
Hi I need the solution showing the work (in details) of this problem. Monthly sales at...
Hi I need the solution showing the work (in details) of this problem. Monthly sales at a coffee shop have been analyzed. The seasonal index values are Month Index Jan 1.38 Feb 1.42 Mar 1.35 Apr 1.03 May 0.99 June 0.62 July 0.51 Aug 0.58 Sept 0.82 Oct 0.82 Nov 0.92 Dec 1.56 and the trend line is 74123 + 26.9(t). Assume there is no cyclical component and forecast sales for year 8 (months 97 - 108).
Note : I need word typed solution for this problem with comprehensive details. Question : Explain...
Note : I need word typed solution for this problem with comprehensive details. Question : Explain the thermal, acoustic and optical properties of lattice vibrations? Please make it to explain all in need.
Read the article entitled "Faster than a Speeding Text" link is here: "Faster than a Speeding...
Read the article entitled "Faster than a Speeding Text" link is here: "Faster than a Speeding Text" by Sigal Barsade and answer the following questions: A. Discuss a communication event in which you experienced emotional contagion. What was the outcome? B. Why is it important to be aware of emotional contagion theory? At work? At home?
Please I need answer for This question and it is very important and I need solution...
Please I need answer for This question and it is very important and I need solution for this issue with all the details just nu , and help me with all the details, so that I can read and understand your answer clearly.thanks in advance/Ha 2. Answer whether the following examples of Foreign Direct Investment (FDI) describe horizontal or vertical FDI. Explain your answers. a) Volvo builds a car factory in Austin, Texas, which is similar to Volvo’s factory in...
Please I need answer for This question and it is very important and I need solution...
Please I need answer for This question and it is very important and I need solution for this issue with all the details just nu , and help me with all the details, so that I can read and understand your answer clearly.I need step by step solution to the following this question asap .I have limited time so please do it quickly with detailed explanation.thanks in advance/Ha Q. In a competitive equilibrium, the equilibrium wage clears the market and...
The optimal solution of the linear programming problem is at the intersection of constraints 1 and...
The optimal solution of the linear programming problem is at the intersection of constraints 1 and 2. Please answer the following questions by using graphical sensitivity analysis. Max s.t. Max 2x1 + x2 s.t. 4x1 +1x2 ≤8 4x1 +3x2 ≤12 1x1 +2x2 ≤6 x1 , x2 ≥ 0 Over what range can the coefficient of x1 vary before the current solution is no longer optimal? Over what range can the coefficient of x2 vary before the current solution is no...
For the following linear programming problem, determine the optimal solution by the graphical solution method Max...
For the following linear programming problem, determine the optimal solution by the graphical solution method Max -x + 2y s.t. 6x - 2y <= 3 -2x + 3y <= 6     x +   y <= 3         x, y >= 0
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT