LeetCode 121 买卖股票的最佳时机

LeetCode 121 买卖股票的最佳时机

给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。

你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。

返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0

示例 1:

复制代码
输入:[7,1,5,3,6,4]
输出:5
解释:在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
     注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。

示例 2:

复制代码
输入:prices = [7,6,4,3,1]
输出:0
解释:在这种情况下, 没有交易完成, 所以最大利润为 0。

提示:

  • 1 <= prices.length <= 105
  • 0 <= prices[i] <= 104

Solution

采用动态规划

java 复制代码
package leetcode.editor.cn;

public class BestTimeToBuyAndSellStock {
    public static void main(String[] args) {
        Solution solution = new BestTimeToBuyAndSellStock().new Solution();
        int[] a = {7, 1, 5, 3, 6, 4};
        solution.maxProfit(a);
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public int maxProfit(int[] prices) {
            int l = prices.length;
            int min_price=Integer.MAX_VALUE,profit=0;
            for (int i = 0; i < l; i++) {
                min_price=Math.min(min_price,prices[i]);
                profit=Math.max(profit,prices[i]-min_price);
            }
            return profit;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}
相关推荐
你也向往长安城吗6 分钟前
推荐一个三维导航库:three-pathfinding-3d
javascript·算法
百度智能云22 分钟前
VectorDB+FastGPT一站式构建:智能知识库与企业级对话系统实战
算法
AI小白的Python之路1 小时前
数据结构与算法-排序
数据结构·算法·排序算法
DashVector1 小时前
如何通过Java SDK检索Doc
后端·算法·架构
zzz9331 小时前
transformer实战——mask
算法
一只鱼^_2 小时前
牛客周赛 Round 105
数据结构·c++·算法·均值算法·逻辑回归·动态规划·启发式算法
是阿建吖!2 小时前
【动态规划】斐波那契数列模型
算法·动态规划
啊阿狸不会拉杆2 小时前
《算法导论》第 27 章 - 多线程算法
java·jvm·c++·算法·图论
火车叨位去19493 小时前
力扣top100(day04-05)--堆
算法·leetcode·职场和发展
数据智能老司机3 小时前
面向企业的图学习扩展——面向图的传统机器学习
算法·机器学习