Best Time to Buy and Sell Stock II



Say you have an array for which the i-th element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

Solution:

The maximum profit is always achieved by buying at the lowest points and selling at the highest points. In other words, we will buy the stock before the price increases, and sell the stock before the price decreases. This could be easily implemented by traversing the array.

The following code passes LeetCode online large judge.
Notes: the complexity is O(n). In this code we need to check the last element in the array. In the for loop we only sell the stock before the price decreases; however, it is possible that the price never goes down. So in the last element, we will sell the stock if we already bought it and we can obtain profit.

Redo it at Sep. 10, 2013. Always buy in the local minimum value, and sell it in the next profitable day.

Comments

  1. Thanks for the solution, it helps much!

    ReplyDelete
  2. Hi man, how did you let your code highlighted?

    ReplyDelete
    Replies
    1. Check this http://alexgorbatchev.com/SyntaxHighlighter/

      Delete

Post a Comment

Popular posts from this blog

Maximum Gap

[ITint5] Maximum Subarray for a Circular Array

[CC150] Chapter 8 Object-Oriented Design