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)

}
相关推荐
L_cl16 分钟前
【Python 算法零基础 3.递推】
算法
int型码农29 分钟前
数据结构第七章(四)-B树和B+树
数据结构·b树·算法·b+树
先做个垃圾出来………1 小时前
汉明距离(Hamming Distance)
开发语言·python·算法
小羊在奋斗2 小时前
【LeetCode 热题 100】二叉树的最大深度 / 翻转二叉树 / 二叉树的直径 / 验证二叉搜索树
算法·leetcode·职场和发展
2301_794461572 小时前
力扣-283-移动零
算法·leetcode·职场和发展
编程绿豆侠2 小时前
力扣HOT100之二叉树:98. 验证二叉搜索树
算法·leetcode·职场和发展
技术流浪者3 小时前
C/C++实践(十)C语言冒泡排序深度解析:发展历史、技术方法与应用场景
c语言·数据结构·c++·算法·排序算法
I AM_SUN3 小时前
98. 验证二叉搜索树
数据结构·c++·算法·leetcode
学习中的码虫4 小时前
数据结构基础排序算法
数据结构·算法·排序算法
yidaqiqi4 小时前
[目标检测] YOLO系列算法讲解
算法·yolo·目标检测