算法奇妙屋(三十六)-贪心算法学习之路3

文章目录

一. 力扣 121. 买卖股票的最佳时机

1. 题目解析

这道题很好理解, 相当于找最大值和最小值的问题

2. 算法原理

3. 代码

java 复制代码
class Solution {
    public int maxProfit(int[] prices) {
        int min = prices[0];
        int ret = 0;
        for (int i = 1; i < prices.length; i++) {
            min = Math.min(min, prices[i]);
            ret = Math.max(ret, prices[i] - min);
        }
        return ret;
    }
}

二. 力扣 122. 买卖股票的最佳时机 II

1. 题目解析

这道题相比于股票问题1, 少了个限制是, 可以多次买卖股票

2. 算法原理

这里提供两种思路, 一种是双指针, 一种是拆分交易, 时间复杂度都是O(N)

(1) 贪心+双指针

(2) 拆分交易

3. 代码

1. 算法1

java 复制代码
class Solution {
    public int maxProfit(int[] prices) {
        int n = prices.length;
        int ret = 0;
        for (int i = 0; i < n;) {
            int j = i;
            while (j < n - 1 && prices[j + 1] > prices[j]) j++;
            ret += prices[j] - prices[i];
            i = j + 1;
        }
        return ret;
    }
}

2. 算法2

java 复制代码
class Solution {
    public int maxProfit(int[] prices) {
        int n = prices.length;
        int ret = 0;
        for (int i = 0; i < n - 1; i++) {
            if (prices[i + 1] > prices[i]) {
                ret += prices[i + 1] - prices[i];
            }
        }
        return ret;
    }
}
相关推荐
Z21-X3 分钟前
云原生运维实战笔记:华为云计算与网络类服务全景解析
运维·笔记·学习·云原生·华为云
redtank20008 分钟前
纯血鸿蒙学习效率三件套实测:背单词艾宾浩斯曲线、时间记录与睡眠辅助
学习·华为·harmonyos
动词ing28 分钟前
【学习笔记】51单片机 模块化编程
笔记·学习·51单片机
Navigator_Z33 分钟前
LeetCode //C - 1313. Decompress Run-Length Encoded List
c语言·算法·leetcode
海绵宝宝转agent1 小时前
计网基础知识
网络·笔记·学习·智能路由器
峯5801 小时前
一文学习FastAPI
学习·fastapi
外收内放1 小时前
ENSP学习记录(6)
开发语言·学习·php
dialect_1 小时前
CODEFORCES ROUND 1127 DIV2
开发语言·c++·算法
Nuanyt1 小时前
LeetCode Hot 100 链表专题(四)· 3 题(Java)
java·算法·leetcode·链表·双指针
灯澜忆梦1 小时前
LeetCode 1861. 旋转盒子|Go 双指针解法
算法