栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

2021.09.28 - 095.买卖股票的最佳时机

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

2021.09.28 - 095.买卖股票的最佳时机

文章目录
  • 1. 题目
  • 2. 思路
    • (1) 动态规划
  • 3. 代码

1. 题目

2. 思路 (1) 动态规划
  • 假设在第i天卖出股票,那么只有在前i-1天中股价最低时买入股票才能获得最高的利润。

  • 变量min记录前i-1天中最低的股价,变量res记录曾经获得的最高利润。

3. 代码
public class Test {
    public static void main(String[] args) {
    }
}

class Solution {
    public int maxProfit(int[] prices) {
        int min = Integer.MAX_VALUE;
        int res = Integer.MIN_VALUE;
        for (int i = 0; i < prices.length; i++) {
            min = Math.min(min, prices[i]);
            res = Math.max(res, prices[i] - min);
        }
        return res;
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/273940.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号