码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode Best Time to Buy and Sell Stock

时间:2015-09-23 13:24:29      阅读:175      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!