LeetCode(算法)- 121. 买卖股票的最佳时机

简介: LeetCode(算法)- 121. 买卖股票的最佳时机

题目链接:点击打开链接

题目大意:

解题思路


8.png


相关企业

  • 字节跳动
  • 微软(Microsoft)
  • 优步(Uber)
  • 谷歌(Google)
  • 苹果(Apple)
  • 甲骨文(Oracle)
  • 彭博(Bloomberg)
  • 高盛集团(Goldman Sachs)
  • Facebook
  • 亚马逊(Amazon)

AC 代码

  • Java
// 解决方案(1)
class Solution {
    public int maxProfit(int[] prices) {
        int cost = Integer.MAX_VALUE, profit = 0;
        for(int price : prices) {
            cost = Math.min(cost, price);
            profit = Math.max(profit, price - cost);
        }
        return profit;
    }
}
// 解决方案(2)
class Solution {
    public int maxProfit(int[] prices) {
        if (prices.length == 0) {
            return 0;
        }
        List<Integer> list = new ArrayList<>();
        // 当前买入最划算指针
        int ptr = 0;
        list.add(prices[ptr]);
        int maxn = prices[ptr];
        for (int i = 1; i < prices.length; i++) {
            int num = prices[i];
            // 当天卖出大于之前的最大卖出值, 直接找到买入最划算指针
            if (num > maxn) {
                maxn = num;
                while (ptr + 1 < list.size()) {
                    ptr++;
                }
            }
            // 当天卖出小于等于之前的最大卖出值, 遍历找出是否存在买入最划算候选指针, 比当前还要划算的
            else {
                for (int j = ptr; j < list.size(); j++) {
                    if (num - list.get(j) > maxn - list.get(ptr)) {
                        maxn = num;
                        ptr = j;
                    }
                }
            }
            // 如果比集合最小的还要小, 说明符合买入最划算的候选指针, 使用 LinkedList 则超时, 获取操作你懂的
            if (num < list.get(list.size() - 1)) {
                list.add(num);
            }
        }
        return maxn - list.get(ptr);
    }
}
  • C++
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int cost = INT_MAX, profit = 0;
        for(int price : prices) {
            cost = min(cost, price);
            profit = max(profit, price - cost);
        }
        return profit;
    }
};
目录
相关文章
|
5天前
|
算法 索引
leetcode代码记录(买卖股票的最佳时机
leetcode代码记录(买卖股票的最佳时机
13 1
|
5天前
|
算法
leetcode代码记录(买卖股票的最佳时机 IV
leetcode代码记录(买卖股票的最佳时机 IV
16 2
|
5天前
|
算法
leetcode代码记录(买卖股票的最佳时机 III
leetcode代码记录(买卖股票的最佳时机 III
13 5
|
5天前
leetcode代码记录(买卖股票的最佳时机 II
leetcode代码记录(买卖股票的最佳时机 II
11 1
|
5天前
|
算法 C++
【刷题】Leetcode 1609.奇偶树
这道题是我目前做过最难的题,虽然没有一遍做出来,但是参考大佬的代码,慢慢啃的感觉的真的很好。刷题继续!!!!!!
9 0
|
5天前
|
算法 索引
【刷题】滑动窗口精通 — Leetcode 30. 串联所有单词的子串 | Leetcode 76. 最小覆盖子串
经过这两道题目的书写,相信大家一定深刻认识到了滑动窗口的使用方法!!! 下面请大家继续刷题吧!!!
12 0
|
5天前
|
算法
【刷题】 leetcode 面试题 08.05.递归乘法
递归算法是一种在计算机科学和数学中广泛应用的解决问题的方法,其基本思想是利用问题的自我相似性,即将一个大问题分解为一个或多个相同或相似的小问题来解决。递归算法的核心在于函数(或过程)能够直接或间接地调用自身来求解问题的不同部分,直到达到基本情况(也称为基础案例或终止条件),这时可以直接得出答案而不必再进行递归调用。
25 4
【刷题】 leetcode 面试题 08.05.递归乘法
|
5天前
|
存储 算法 安全
【刷题】 leetcode 面试题 01.06 字符串压缩
来看效果: 非常好!!!过啦!!!
27 5
【刷题】 leetcode 面试题 01.06 字符串压缩
|
5天前
|
存储 算法 测试技术