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

[LeetCode] Best Time to Buy and Sell Stock

时间:2015-08-17 14:00:01      阅读:147      评论: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.

 

     这道题就不仅仅只是算法题了,我们还要考虑到生活中的常识。

     比如这个是Buy and Sell,就说明我们必须是先Buy然后再Sell。

     比如第五天价格最低,第三天价格最高,我们肯定不能第五天买了然后穿越回去第三天卖出去啊。所以loop的时候要考虑到这些因素。

     代码如下。~

public class Solution {
    public int maxProfit(int[] prices) {
        //special case
        if(prices==null||prices.length<2){
            return 0;
        }
        int min=prices[0];
        int profit=0;
        for(int i=0;i<prices.length;i++){
            if(profit<(prices[i]-min)){
                profit=prices[i]-min;
            }else if(prices[i]<min){
                min=prices[i];
            }
        }
        return profit;
    }
}

 

[LeetCode] Best Time to Buy and Sell Stock

标签:

原文地址:http://www.cnblogs.com/orangeme404/p/4736289.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!