Leetcode Best Time to Buy and Sell Stock

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

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.


解题思路:

本题原来做错的原因是我原以为只要找到最小值和最大值,相减就能得到最大的利润。但股票买卖是有顺序的,先买后卖。因此最小值必须是左边的,然后比较右边的值与最小值的差异,最大的就是最大利润。

Scan from left to right. And keep track the minimal price in left. So, each step, only calculate the difference between current price and minimal price.
If this diff large than the current max difference, replace it.


 Java code

 public int maxProfit(int[] prices) {
       int profit = 0;
       int min = Integer.MAX_VALUE;
       for(int i = 0; i < prices.length; i++) {
           min = Math.min(min, prices[i]);
           profit = Math.max(profit, prices[i] - min);
       }
       return profit;
    }

Reference:

1. http://fisherlei.blogspot.com/2013/01/leetcode-best-time-to-buy-and-sell.html

2. http://www.programcreek.com/2014/02/leetcode-best-time-to-buy-and-sell-stock-java/

 

posted @ 2015-09-23 12:46  茜茜的技术空间  阅读(166)  评论(0编辑  收藏  举报