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;
        }
  • 相关阅读:
    用户控件JS问题
    jQuery formValidator自定义函数扩展功能
    IAR使用notice
    C++入门学习
    解决Myeclipse闪退问题
    Cortex_M3——存储器系统学习笔记
    加密算法中涉及C/C++总结
    学习笔记——应用密码学基础
    keil软件相关问题汇总
    STM32知识点纪要
  • 原文地址:https://www.cnblogs.com/savageclc26/p/4871251.html
Copyright © 2011-2022 走看看