If you know the future prices of a stock, what's the best time to buy and sell?

前端 未结 5 596
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-09 21:22

Interview Question by a financial software company for a Programmer position

Q1) Say you have an array for which the ith element is the price of a giv

5条回答
  •  醉话见心
    2020-12-09 21:57

    Here are some alternative answers:

    Q1) Work from left to right in the array provided. Keep track of the lowest price seen so far. When you see an element of the array note down the difference between the price there and the lowest price so far, update the lowest price so far, and keep track of the highest difference seen. My answer is to make the amount of profit given at the highest difference by selling then, after having bought at the price of the lowest price seen at that time.

    Q2) Treat this as a dynamic programming problem, where the state at any point in time is whether you own a share or not. Work from left to right again. At each point find the highest possible profit, given that own a share at the end of that point in time, and given that you do not own a share at the end of that point in time. You can work this out from the result of the calculations of the previous time step: In one case compare the options of buying a share and subtracting this from the profit given that you did not own at the end of the previous point or holding a share that you did own at the previous point. In the other case compare the options of selling a share to add to the profit given that you owned at the previous time, or staying pat with the profit given that you did not own at the previous time. As is standard with dynamic programming you keep the decisions made at each point in time and recover the correct list of decisions at the end by working backwards.

提交回复
热议问题