资讯专栏INFORMATION COLUMN

leetcode 121 Best Time to Buy and Sell Stock

QLQ / 2571人阅读

摘要:求可能的最大利润题目给了两个例子最大利润就是进价为,卖价为的时候,利润为在这个案例中,进价一直高于售价,所以无法成交,返回。主要注意一下,先买入才能卖出卖价一定要比买入价格高才能成交就可以了。

题目详情
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
这道题描述的意思就是,给定一个数组prices,里面的第i个元素就是商品第i天的价格。我们要选择某天买入,某天卖出(卖出操作肯定在买入操作之后)。求可能的最大利润

题目给了两个例子
Example 1:
Input: [7, 1, 5, 3, 6, 4]
Output: 5
最大利润就是进价为1,卖价为6的时候,利润为5.
Example 2:
Input: [7, 6, 4, 3, 1]
Output: 0
在这个案例中,进价一直高于售价,所以无法成交,返回0。

理解

这道题理解了其实是比较简单的。主要注意一下,先买入才能卖出、卖价一定要比买入价格高才能成交就可以了。

解法
    public int maxProfit(int[] prices) {
        int maxProfit = 0;
        int minBuyPrice = 0;
        
        if(prices.length <= 1){
            return 0;
        }
        
        minBuyPrice = prices[0];
        
        for(int i=1;i maxProfit){
                maxProfit = curPrice - minBuyPrice;
            }
        }
        
        return maxProfit;
    }

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/68233.html

相关文章

  • 121. Best Time to Buy and Sell Stock

    121. Best Time to Buy and Sell Stock Say you have an array for which the ith element is the price of a given stock on day i.If you were only permitted to complete at most one transaction (i.e., buy on...

    Tecode 评论0 收藏0
  • [LeetCode]Best Time to Buy and Sell Stock with Coo

    摘要:分析因为当前日期买卖股票会受到之前日期买卖股票行为的影响,首先考虑到用解决。所以我们可以用两个数组分别记录当前持股跟未持股的状态。 Best Time to Buy and Sell Stock with Cooldown Say you have an array for which the ith element is the price of a given stock on ...

    xcc3641 评论0 收藏0
  • LeetCode 309. Best Time to Buy and Sell Stock with

    摘要:示例输入输出解释对应的交易状态为买入卖出冷冻期买入卖出思路这道题使用动态规划。状态表示当天休息能够获得的最大价值,表示当天持有股票能够获得的最大价值,表示当天持有股票能够获得的最大价值。 Description Say you have an array for which the ith element is the price of a given stock on day i. ...

    刘明 评论0 收藏0
  • Best Time To Buy And Sell Stock 买卖股票最佳时机

    摘要:关键字,,算法,,动态规划,上关于主题的题目有四个这四个题目难度依次递增。其中第四个问题是寻求一个通解,在给定和最大买卖次数的情况下,求最大收益。首先大致的解题方向是动态规划,这个应该不难想到。之后就是怎么找到状态,怎么列状态转移方程。 关键字:leetcode,Best Time To Buy And Sell Stock,算法,algorithm,动态规划,dynamic prog...

    elliott_hu 评论0 收藏0
  • Leetcode188. Best Time to Buy and Sell Stock IV

    摘要:题目要求有一个整数数组,每一位上的值代表那一天的股票价格。现在假设最多能够进行次交易,问最大的收入是多少思路和代码这里采用了动态编程的思想。 题目要求 Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find t...

    pingink 评论0 收藏0

发表评论

0条评论

QLQ

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<