zoukankan      html  css  js  c++  java
  • 剑指Offer对答如流系列

    面试题63:股票的最大利润

    题目描述

    假设把某股票的价格按照时间先后顺序存储在数组中,请问买卖交易该股票可能获得的利润是多少?例如一只股票在某些时间节点的价格为{9, 11, 8, 5,7, 12, 16, 14}。如果我们能在价格为5的时候买入并在价格为16时卖出,则能收获最大的利润11。

    问题分析

    这道题很容易想到贪心算法:遍历每一个数字,并保存之前最小的数字,两者差最大即为最大利润。

    不过这也有一个数学模型,叫做峰谷求值

    在这里插入图片描述

    专注点在于这种图表的连续的峰和谷。

    更多的情况是关注它的差值:

    用数学语言描述为:
    在这里插入图片描述

    问题解决

        public int maxProfit(int[] prices) {
            int i = 0;
            int valley = prices[0];
            int peak = prices[0];
            int maxprofit = 0;
            while (i < prices.length - 1) {
                while (i < prices.length - 1 && prices[i] >= prices[i + 1]) {
                    i++;
                }
                valley = prices[i];
                while (i < prices.length - 1 && prices[i] <= prices[i + 1]) {
                    i++;
                }
                peak = prices[i];
                maxprofit += peak - valley;
            }
            return maxprofit;
        }
    
  • 相关阅读:
    Deployment.yaml文件
    Python 闭包
    github使用方法(一)
    7.Python 正则表达式学习笔记
    kindle网络爬虫续集
    windows下如何快速搭建web.py开发框架
    Python强大的自省简析
    11--Python 备份文件程序
    10- python 网络爬虫分析
    Python基础学习7---异常处理
  • 原文地址:https://www.cnblogs.com/JefferyChenXiao/p/12249474.html
Copyright © 2011-2022 走看看