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

LeetCode-121 Best Time to Buy and Sell Stock

时间:2015-01-21 21:57:11      阅读:174      评论: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.

 

解法1:

找到每个极小值,从每个极小值之后找一个最大值,计算最大收益。比较每个最大收益。

public class Solution {
    public int maxProfit(int[] prices) {
        if(prices == null || prices.length == 0 || prices.length == 1)
            return 0;
            
        int maxprofit = Integer.MIN_VALUE;
        int dateIn = 0;
        
        while(dateIn < prices.length - 1) {
            //find a bottom
            while(dateIn < prices.length - 1 && prices[dateIn] >= prices[dateIn+1])
                dateIn++;
            
            
            for(int i=dateIn+1; i<prices.length; i++) {
                if(prices[i] - prices[dateIn] > maxprofit) {
                    maxprofit = prices[i] - prices[dateIn];
                }
            }
            
            //find a top
            while(dateIn < prices.length - 1 && prices[dateIn] <= prices[dateIn+1])
                dateIn++;
        }
        
        return maxprofit == Integer.MIN_VALUE ? 0 : maxprofit;
    }
}

 

解法2:

先整理数据,计算后一个元素相对前一个元素的差值,第一个元素为0,如1,4,2整理后为0,3,-2;

计算一个连续的数组元素的和,求和的最大值。

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

 

LeetCode-121 Best Time to Buy and Sell Stock

标签:

原文地址:http://www.cnblogs.com/linxiong/p/4240086.html

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