zoukankan      html  css  js  c++  java
  • [LeetCode]: 121: Best Time to Buy and Sell Stock

    题目:

    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.

    分析:一维的动态规划(硬算就行吧)

    设dp[i]是[0,1,2...i]区间的最大利润,则该问题的一维动态规划方程如下

    dp[i+1] = max{dp[i], prices[i+1] - minprices}  ,minprices是区间[0,1,2...,i]内的最低价格

    我们要求解的最大利润 = max{dp[0], dp[1], dp[2], ..., dp[n-1]} 

    其实关键就是一个是维护最大的利润的记录,一个是维护最大,最小值的记录。且最大值和最小值的其中一个需要和最大利润联动

    代码:

        public int maxProfit(int[] prices) {
            if(prices == null || prices.length == 0){
                return 0;
            }
    
            int Profit = 0;
            int Min = prices[0];
            int Max = prices[0];
            
            for(int i =1 ;i<prices.length;i++ ){
                if(prices[i] - Min > Profit){
                    Max = prices[i];
                    Profit = Max - Min;
                }else if(prices[i] - Min < Profit &&  prices[i] < Min){
                    Min = prices[i];
                }
            }
            
            return Profit;
        }
  • 相关阅读:
    STL(五)list
    WinCE进程ID获取窗口句柄
    【转】.obj, .lib, .dll, .exe的关系
    《Windows核心编程》——线程
    【转】windows结束线程方式
    VS2005调试多进程
    【转】VC中常用的宏
    【转】C++标准库简介
    WinCE下用STL的奇怪问题
    STL(三)string
  • 原文地址:https://www.cnblogs.com/savageclc26/p/4871251.html
Copyright © 2011-2022 走看看