【LeetCode】第1天 - 121.买卖股票的最佳时机

简介: LeetCode121题:121.买卖股票的最佳时机

@TOC

题目描述

在这里插入图片描述

解题思路

1 . 两次遍历(i, j)价格数组,找出卖出和买入的最大差值(max(prices[j] - prices[i]))。

  • i: 0 ~ prices.length - 2 ; i 只需遍历至数组的倒数第二个元素
  • j: i + 1 ~ prices.length - 1

2 . 一次遍历价格数组(i),每天更新当前历史最低点(minPrice),更新当前最大利润(maxProfit = prices[i] - minPrices)。

代码实现

1 . 思路1

public class Solution {
    public int maxProfit(int prices[]) {
        int maxProfit = 0;    //记录当前可以获得的最大利润
        int length = prices.length;        //获取价格数组长度
        for (int i = 0; i < length-1; i++) {
            for (int j = i + 1; j < prices.length; j++) {
                if (prices[j] - prices[i]> maxProfit) {
                    maxProfit = prices[j] - prices[i];        //更新最大利润
                }
            }
        }
        return maxProfit;
    }
}

2 . 思路2

class Solution {
    public int maxProfit(int[] prices) {
        if(prices.length <= 1){
            return 0;
        }
        int maxProfit = 0;
        int minPrice = prices[0];    //记录当前历史最低点
        for(int i=1; i<prices.length; i++){
            if(prices[i]<minPrice){
                minPrice = prices[i];    //更新历史最低点
            }else if(prices[i] - minPrice > maxProfit){
                maxProfit = prices[i] - minPrice;    //更新最大利润
            }
        }

        return maxProfit;
    }
}
目录
相关文章
|
2天前
|
算法 索引
leetcode代码记录(买卖股票的最佳时机
leetcode代码记录(买卖股票的最佳时机
13 1
|
2天前
|
算法
leetcode代码记录(买卖股票的最佳时机 IV
leetcode代码记录(买卖股票的最佳时机 IV
14 2
|
2天前
|
算法
leetcode代码记录(买卖股票的最佳时机 III
leetcode代码记录(买卖股票的最佳时机 III
13 5
|
2天前
leetcode代码记录(买卖股票的最佳时机 II
leetcode代码记录(买卖股票的最佳时机 II
9 1
|
2天前
|
算法 C++
【刷题】Leetcode 1609.奇偶树
这道题是我目前做过最难的题,虽然没有一遍做出来,但是参考大佬的代码,慢慢啃的感觉的真的很好。刷题继续!!!!!!
9 0
|
2天前
|
算法 索引
【刷题】滑动窗口精通 — Leetcode 30. 串联所有单词的子串 | Leetcode 76. 最小覆盖子串
经过这两道题目的书写,相信大家一定深刻认识到了滑动窗口的使用方法!!! 下面请大家继续刷题吧!!!
12 0
|
2天前
|
算法
【刷题】 leetcode 面试题 08.05.递归乘法
递归算法是一种在计算机科学和数学中广泛应用的解决问题的方法,其基本思想是利用问题的自我相似性,即将一个大问题分解为一个或多个相同或相似的小问题来解决。递归算法的核心在于函数(或过程)能够直接或间接地调用自身来求解问题的不同部分,直到达到基本情况(也称为基础案例或终止条件),这时可以直接得出答案而不必再进行递归调用。
25 4
【刷题】 leetcode 面试题 08.05.递归乘法
|
2天前
|
存储 算法 安全
【刷题】 leetcode 面试题 01.06 字符串压缩
来看效果: 非常好!!!过啦!!!
25 5
【刷题】 leetcode 面试题 01.06 字符串压缩
|
2天前
|
存储 算法 测试技术