Question

(5 +2 points) You are given an array A[1..n] of positive numbers where Ai] is the stock price on day i. You are allowed to bu

0 0
Add a comment Improve this question Transcribed image text
Answer #1

PSEUDO CODE:

def minimumLoss(price):
    price_map = []

    # price_map wil store records of (PRICE, DAY)
    for i in range(len(price)):
        price_map.append([price[i], i])

    # sort the price_map based on the PRICE
    price_map.sort(key=lambda x:x[0])

    bought_day = -1
    sold_day = -1
    currrent_profit = 0
    i = 0
    j = len(price_map) - 1
    while i != j:
       # if the sold day is greater than bought date
        if price_map[i][1] < price_map[j][1]:
           # compute the profit
            profit = abs(price_map[i][0] - price_map[j][0])

            # if profit greater than current profit
            if profit > current_profit:
               current_profit = profit
               bought_day = price_map[j][0]
               sold_day = price_map[i][0]]

        i += 1
        j -= 1

    return bought_day, sold_day

EXPLANATION:

First the given array A is considered and an extra storage price_map is taken.
price_map contains records as (PRICE, DAY).

Then the price_map is sorted according to the price.
The difference is calculated from the extreme corners with a condition such that the sold day should be after bought day.
This is done using the DAY attribute in the price_map records.
The maximum profit day is considered and it is saved in bought_day and sold_day and returned.

Here, the two key operations are sorting and linear traversal.
So f(n) = sort + linear traversal, but sorting can be done in n log n and linear traversal in n
implies, f(n) = n log n + n
Therefore O(n) = n log n.

Add a comment
Know the answer?
Add Answer to:
(5 +2 points) You are given an array A[1..n] of positive numbers where Ai] is the stock price on ...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT