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

LeetCode -- Best Time to Buy and Sell Stock

时间:2015-09-18 21:48:13      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:

Question:

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.

 

Analysis:

问题描述:给出一个数组,其中第i个元素表示第i天的股票售价。如果只允许一次买入卖出,请给出最大利润方案(即在第i天买入,第j天卖出使得利益最大)。

思路:要求保证在 i < j 的前提下,找出数组中最大和最小的元素,两者之间的差就是最大利润。因此用一个指针指向最低元素(若当前元素的值比史上最低值还低,则指向该元素),一个整数保存目前的利润(如果当前元素减去最低值还要大于已有利润,则更新一下)。

 

Answer:

public class Solution {
      public static int maxProfit(int[] prices) {
            if(prices.length == 0 || prices.length == 1)
                return 0;
        int low = prices[0];
        int profile = 0;
        for(int i=1; i<prices.length; i++) {
                if(prices[i] < low)
                    low = prices[i];
                if(prices[i] - low > profile)
                    profile = prices[i] - low;
        }
        return profile;
    }
 
}

 

LeetCode -- Best Time to Buy and Sell Stock

标签:

原文地址:http://www.cnblogs.com/little-YTMM/p/4820348.html

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