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)

}
相关推荐
爱数模的小云1 分钟前
【华为杯】2024华为杯数模研赛D题 解题思路
算法·华为
好记性+烂笔头35 分钟前
hot100-438. 找到字符串中所有字母异位词
算法
六点半8881 小时前
【C/C++】速通涉及string类的经典编程题
c语言·开发语言·c++·算法
@听风吟1 小时前
力扣之182.查找重复的电子邮箱
大数据·javascript·数据库·sql·leetcode
学地理的小胖砸2 小时前
【高分系列卫星简介】
开发语言·数码相机·算法·遥感·地理信息
__AtYou__3 小时前
Golang | Leetcode Golang题解之第417题太平洋大西洋水流问题
leetcode·golang·题解
yanyanwenmeng3 小时前
matlab基础
开发语言·算法·matlab
##晴天小猪3 小时前
ByteTrack多目标跟踪流程图
人工智能·算法·目标检测·机器学习·目标跟踪
Ddddddd_1583 小时前
C++ | Leetcode C++题解之第421题数组中两个数的最大异或值
c++·leetcode·题解
ly-how3 小时前
leetcode练习 二叉树的层序遍历
算法·leetcode