LeetCode(剑指 Offer)- 63. 股票的最大利润

简介: LeetCode(剑指 Offer)- 63. 股票的最大利润

题目链接:点击打开链接

题目大意:

解题思路


7.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;
    }
};
目录
相关文章
|
2月前
|
算法
《LeetCode》—— 买卖股票的最佳时机
《LeetCode》—— 买卖股票的最佳时机
|
2天前
|
算法
leetcode代码记录(买卖股票的最佳时机 IV
leetcode代码记录(买卖股票的最佳时机 IV
9 2
|
2天前
|
算法
leetcode代码记录(买卖股票的最佳时机 III
leetcode代码记录(买卖股票的最佳时机 III
11 5
|
2天前
leetcode代码记录(买卖股票的最佳时机 II
leetcode代码记录(买卖股票的最佳时机 II
7 1
|
2天前
|
算法 索引
leetcode代码记录(买卖股票的最佳时机
leetcode代码记录(买卖股票的最佳时机
8 1
|
25天前
|
算法 定位技术
【leetcode】剑指 Offer II 105. 岛屿的最大面积-【深度优先DFS】
【leetcode】剑指 Offer II 105. 岛屿的最大面积-【深度优先DFS】
17 0
|
26天前
|
算法
【力扣】121. 买卖股票的最佳时机、122.买卖股票的最佳时机Ⅱ
【力扣】121. 买卖股票的最佳时机、122.买卖股票的最佳时机Ⅱ
|
1月前
|
算法
【力扣经典面试题】121. 买卖股票的最佳时机
【力扣经典面试题】121. 买卖股票的最佳时机
|
2月前
|
算法
leetcode121. 买卖股票的最佳时机
leetcode121. 买卖股票的最佳时机
14 0
|
2月前
|
安全 测试技术
leetcode1599 经营摩天轮的最大利润
leetcode1599 经营摩天轮的最大利润
24 0

热门文章

最新文章