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

LeetCode Best Time to Buy and Sell Stock

时间:2015-03-29 13:41:22      阅读:186      评论: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.

思路分析:这题需要用到动态规划,具体来说需要维护局部最优和全局最优变量。局部最优用于保存在当前第i天卖出的情况中的最大利润,而全局最优是从开始到第i天的全局最大利润,假设我们已经知道了local[i]和global[i],递推计算i+1的情况的公式为:local[i+1] =  Math.max(local[i] + diff, 0)。其中diff为prices[i+1]-prices[i]; global[i+1]=Math.max(global[i], local[i+1]);有了递推方程就好实现了,时间复杂度为O(n),空间复杂度为O(1)(只需要使用两个变量).

AC  Code

public class Solution {
    public int maxProfit(int[] prices) {
        //1124
        if(prices == null || prices.length < 1){
            return 0;
        }
        int localmax = 0;
        int globalmax = 0;
        for(int i = 0; i < prices.length - 1; i++){
            int diff = prices[i+1] -  prices[i];
            localmax = Math.max(localmax + diff, 0);
            globalmax = Math.max(localmax, globalmax);
        }
        return globalmax;
    }
}


LeetCode Best Time to Buy and Sell Stock

标签:

原文地址:http://blog.csdn.net/yangliuy/article/details/44725841

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