当前位置:   article > 正文

Leetcode 买卖股票的最佳时机_买卖股票最佳时间leetcode

买卖股票最佳时间leetcode

买卖股票的最佳时机

题目描述:

给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。
你只能选择 某一天买入这只股票,并选择在 未来的某一个不同的日子卖出该股票。设计一个算法来计算你所能获取的最大利润。
返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。

题目链接

// 暴力解法超时
class Solution {
    public int maxProfit(int[] prices) {
        int len = prices.length;
        int max = 0;
        for(int i = 1 ; i<len ; i++){
            for(int j = 0 ; j<i ; j++){
                int temp = prices[i] - prices[j];
                max = temp>max  ? temp : max;
            }    
        }
        return max;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
继续改进后…
public class Solution {
    public int maxProfit(int prices[]) {
        int minprice = Integer.MAX_VALUE;
        int maxprofit = 0;
        for (int i = 0; i < prices.length; i++) {
            if (prices[i] < minprice) { // 选择最小的买入
                minprice = prices[i];
            } else if (prices[i] - minprice > maxprofit) { // 更新最大利润
                maxprofit = prices[i] - minprice;
            }
        }
        return maxprofit;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

这里理解题意即可解决,对每一天我们需要选择最低的买入价格,然后在之后的天考虑可获利的最大价格以及继续考虑最低的买入价格,而且需要利用全局变量保存最大的利润。详细请看代码,有疑问欢迎留言。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/499964
推荐阅读
相关标签
  

闽ICP备14008679号