【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;
    }
}
目录
相关文章
|
算法 Python
【Leetcode刷题Python】309. 最佳买卖股票时机含冷冻期
解决LeetCode上309题“最佳买卖股票时机含冷冻期”的Python代码示例,利用动态规划方法计算在含有冷冻期约束下的最大利润。
252 1
|
算法 Python
【Leetcode刷题Python】121. 买卖股票的最佳时机
解决LeetCode上121题“买卖股票的最佳时机”的Python代码示例,采用一次遍历的方式寻找最佳买卖时机以获得最大利润。
423 1
|
算法
leetcode188 买卖股票的最佳时机IV
leetcode188 买卖股票的最佳时机IV
301 0
|
算法 Python
【Leetcode刷题Python】714. 买卖股票的最佳时机含手续费
提供了两种解决买卖股票最佳时机含手续费问题的Python实现方法:贪心算法和动态规划算法。
313 0
|
算法 Python
【Leetcode刷题Python】122.买卖股票的最佳时机 II
LeetCode "买卖股票的最佳时机 II" 问题的Python代码实现,采用贪心算法在股票价格上升的每一天买入并卖出,以获得最大利润。
414 0
|
算法
leetcode题解:121.买卖股票的最佳时机
leetcode题解:121.买卖股票的最佳时机
288 0
|
Unix Shell Linux
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行
本文提供了几个Linux shell脚本编程问题的解决方案,包括转置文件内容、统计词频、验证有效电话号码和提取文件的第十行,每个问题都给出了至少一种实现方法。
626 6
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行
|
Python
【Leetcode刷题Python】剑指 Offer 32 - III. 从上到下打印二叉树 III
本文介绍了两种Python实现方法,用于按照之字形顺序打印二叉树的层次遍历结果,实现了在奇数层正序、偶数层反序打印节点的功能。
305 6
|
搜索推荐 索引 Python
【Leetcode刷题Python】牛客. 数组中未出现的最小正整数
本文介绍了牛客网题目"数组中未出现的最小正整数"的解法,提供了一种满足O(n)时间复杂度和O(1)空间复杂度要求的原地排序算法,并给出了Python实现代码。
651 2
|
数据采集 负载均衡 安全
LeetCode刷题 多线程编程九则 | 1188. 设计有限阻塞队列 1242. 多线程网页爬虫 1279. 红绿灯路口
本文提供了多个多线程编程问题的解决方案,包括设计有限阻塞队列、多线程网页爬虫、红绿灯路口等,每个问题都给出了至少一种实现方法,涵盖了互斥锁、条件变量、信号量等线程同步机制的使用。
593 4
LeetCode刷题 多线程编程九则 | 1188. 设计有限阻塞队列 1242. 多线程网页爬虫 1279. 红绿灯路口