算法奇妙屋(三十六)-贪心算法学习之路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;
    }
}
相关推荐
一隅论数智19 小时前
给AI一张“业务概念地图“:本体如何从哲学走向企业智能
大数据·人工智能·经验分享·笔记·学习·学习方法·政务
倒头就睡的小比特19 小时前
算法竞赛C++常用的STL
c++·算法
小羊没烦恼!19 小时前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
XiHongShi201619 小时前
STM32F407 RTC定时器例程,建议保存
stm32·单片机·学习
爱吃苹果的日记本20 小时前
离散数学第六课
学习·离散数学
猎头南楼20 小时前
知识社区推荐系统实践:新用户冷启动与长短期兴趣建模的挑战 资深推荐算法工程师
人工智能·深度学习·算法·机器学习
AI职业加油站21 小时前
AI智能体应用工程师证书:政策红利下的职业新风口
大数据·运维·人工智能·学习·职场发展
旖旎夜光21 小时前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控
wzdark21 小时前
大规模并行计算中的负载均衡算法研究4
算法