Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7572521
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T15:56:47+00:00 2026-05-30T15:56:47+00:00

I was asked this question while interviewing for a startup and saw this again

  • 0

I was asked this question while interviewing for a startup and saw this again in the recent contest at

Code Sprint:systems

**The question :

You are given the stock prices for a set of days . Each day, you can either buy one unit of stock, sell any number of stock units you have already bought, or do nothing. What is the maximum profit you can obtain by planning your trading strategy optimally?**

Examples ( The input i.e the no of days can vary )

5 3 2 => profit = 0 // since the price decreases each day ,the max profit we can make = 0

1 2 100 => profit = 197

1 3 1 2 =>profit = 3 // we buy at 1 sell at 3 , then we buy at 1 and sell at 2 ..total profit = 3

My Solution :

a) Find the day when the stock price was largest . Keep buying 1 unit of stock till that day.

b) If that day is the last day then quit:

else:
Sell all the stocks on that day and split the array after that day and recurse on the remaining elements
c) merge the profits

e.g 1 4 1 2 3
a) highest stock price on day 2 .. so we buy stock on day 1 and sell it on day 2 ( profit = 3 ) then we recurse on the remaining days : 1 2 3

b) Max price is 3 ( on day 5) so we keep buying stock on day 3 and day 4 and sell on day 5 ( profit = ( 3*2 – 3 = 3 )

c) Total profit = 3 + 3 = 6

The complexity for this turns out to be O(n^2) . this solution passed 10 of the 11 cases but exceeded the time limit on a last test case (i.e the largest input)

Can anyone think of a more efficient solution to this problem? Is there a dynamic programming solution ?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-30T15:56:48+00:00Added an answer on May 30, 2026 at 3:56 pm

    I agree with the logic of your method but there is no need to do recursive processing or global maxima searches. To find the sell/buy days you just need to look at each day once:

    The trick is to start from the end. Stock trade is easy if your travel backwards in time!

    If you think code is easier to read than words, just skip my explanation, but here goes:

    Reading from the end, look at price of that day. Is this the highest price so far (from the end), then sell! The last day (where we start reading) you will always sell.

    Then go to the next day (remember, backwards in time). Is it the highest price so far (from all we looked at yet)? – Then sell all, you will not find a better day. Else the prices increase, so buy. continue the same way until the beginning.

    The whole problem is solved with one single reverse loop: calculating both the decisions and the profit of the trade.

    Here’s the code in C-like python: (I avoided most pythonic stuff. Should be readable for a C person)

    def calcprofit(stockvalues): 
        dobuy=[1]*len(stockvalues) # 1 for buy, 0 for sell
        prof=0
        m=0
        for i in reversed(range(len(stockvalues))):
            ai=stockvalues[i] # shorthand name
            if m<=ai:
                dobuy[i]=0
                m=ai
            prof+=m-ai
        return (prof,dobuy)  
    

    Examples:

    calcprofit([1,3,1,2]) gives (3, [1, 0, 1, 0])
    calcprofit([1,2,100]) gives (197, [1, 1, 0])
    calcprofit([5,3,2])   gives (0, [0, 0, 0])
    calcprofit([31,312,3,35,33,3,44,123,126,2,4,1]) gives
     (798, [1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0])
    

    Note that m is the highest stock price we have seen (from the end). If ai==m then the profit from stocks bought at the the step is 0: we had decreasing or stable price after that point and did not buy.

    You can verify that the profit calculation is correct with a simple loop (for simplicity imagine it’s within the above function)

    stock=0
    money=0
    for i in range(len(stockvalues)):  
        if dobuy[i]:
            stock+=1
            money-=stockvalues[i]
        else:
            money+=stockvalues[i]*stock
            stock=0
    print("profit was: ",money)
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I asked this question a while back but now I'm looking to implement an
This question was asked quite some time ago, and while it covers possible solutions
While interviewing for a company, I was asked to submit several code samples that
UPDATE 10/19/2010 I know I asked this question a while ago, but the workarounds
Edit: While this question has been asked and answered before ( 1 ), (
This question is related to this initial question asked a little while ago. Now,
A while ago I asked this question about how to defer updates to an
While this question asked something similar too, I'm interested in this from another angle.
While this question has been asked in a variety of contexts before, I can't
So earlier I asked this question: JQuery Login Redirect. Code Included The php file

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.