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

前端 未结 5 586
佛祖请我去吃肉
佛祖请我去吃肉 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 22:03

    Your solution for first problem is Correct. Kadane's Algorithm runtime complexity is O(n) is a optimal solution for maximum subarray problem. And benefit of using this algorithm is that it is easy to implement.

    Your solution for second problem is wrong according to me. What you can do is to store the left and right index of maximum sum subarray you find. Once you find have maximum sum subarray and its left and right index. You can call this function again on the left part i.e 0 to left -1 and on right part i.e. right + 1 to Array.size - 1. So, this is a recursion process basically and you can further design the structure of this recursion with base case to solve this problem. And by following this process you can maximize profit.

提交回复
热议问题