首页 > 其他 > 详细

Leetcode Best Time to Buy and Sell Stock

时间:2015-09-23 13:23:09      阅读:280      评论:0      收藏:0      [点我收藏+]

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/

 

Leetcode Best Time to Buy and Sell Stock

原文:http://www.cnblogs.com/anne-vista/p/4831906.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!