hgq's docs
主页
ES6-阮一峰 (opens new window)
Vue文档 (opens new window)
Axios文档 (opens new window)
Vue Router (opens new window)
Vuex文档 (opens new window)
面试题-Vue (opens new window)
面试题-JS (opens new window)

guoguoqiqi

漫不经心的向往
主页
ES6-阮一峰 (opens new window)
Vue文档 (opens new window)
Axios文档 (opens new window)
Vue Router (opens new window)
Vuex文档 (opens new window)
面试题-Vue (opens new window)
面试题-JS (opens new window)
  • 反转链表
  • 无重复字符的最长子串
  • LRU 缓存
  • 数组中的第K个最大元素
  • K个一组翻转链表
  • 三数之和
  • 手撕快速排序
  • 最大子数组和
  • 两数之和
  • 合并两个有序链表
  • 环形链表
  • 二叉树的层序遍历
  • 买卖股票的最佳时机
    • 二叉树的锯齿形层序遍历
    • 相交链表
    • 有效的括号
    • 二叉树的最近公共祖先
    • 合并两个有序数组
    • 搜索旋转排序数组
    • 最长回文子串
    • 岛屿的数量
    • 全排列
    • 字符串相加
    • 高频算法题
    guoguoqiqi
    2022-03-17

    买卖股票的最佳时机

    给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。

    你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。

    返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。

    示例 1:

    输入:[7,1,5,3,6,4]
    输出:5
    解释:在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
         注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。
    
    1
    2
    3
    4

    # 解法:一次遍历

    /**
     * @param {number[]} prices
     * @return {number}
     */
    const maxProfit = prices => {
        // 先定义第一天为最低价格
        let min = prices[0];
        // 利润
        let profit = 0;
        // 遍历数据
        for (let i = 1; i < prices.length; i++) {
            // 如果发现比最低价格还低的,更新最低价格
            min = Math.min(min, prices[i]);
            // 如果发现当前利润比之前高的,更新利润
            profit = Math.max(profit, prices[i] - min);
        }
        return profit;
    };
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18

    来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock

    ← 二叉树的层序遍历 二叉树的锯齿形层序遍历→

    最近更新
    01
    vuex数据持久化怎么做
    05-22
    02
    vue的动态路由怎么配置使用
    05-22
    03
    vue权限控制一般怎么做
    05-22
    更多文章>
    Theme by Vdoing | Copyright © 2022-2022 Guoquoqiqi | MIT License
    • 跟随系统
    • 浅色模式
    • 深色模式
    • 阅读模式