资讯专栏INFORMATION COLUMN

LeetCode-Best Time to Buy and Sell Stock

FullStackDeveloper / 2615人阅读

摘要:注意你不能在买入股票前卖出股票。示例输入输出解释在这种情况下没有交易完成所以最大利润为。解答这里要注意的一点就是不能直接求出最大的和最小的然后相减得出结果,因为买和卖是由顺序关系的,买必须在卖之前,代码如下

发布自Kindem的博客,欢迎大家转载,但是要注意注明出处
题目

给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。

如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。

注意你不能在买入股票前卖出股票。

示例 1:

输入: [7,1,5,3,6,4]
输出: 5
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
     注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。

示例 2:

输入: [7,6,4,3,1]
输出: 0
解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。
解答

这里要注意的一点就是不能直接求出最大的和最小的然后相减得出结果,因为买和卖是由顺序关系的,买必须在卖之前,JavaScript代码如下:

/**
 * @param {number[]} prices
 * @return {number}
 */
let maxProfit = (prices) => {

    let ans = 0;

    for (let i = 0 ; i < prices.length; i++) {

        let arr = [];

        for (let j = i + 1; j < prices.length; j++)
            arr.push(prices[j] - prices[i]);

        let max = 0;

        for (let j = 0; j < arr.length; j++)
            if (arr[j] > max) max = arr[j];

        ans = max > ans ? max : ans;

    }

    return ans;

};

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

转载请注明本文地址:https://www.ucloud.cn/yun/96458.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
  • 309. Best Time to Buy and Sell Stock with Cooldown

    摘要:题目链接来解,要用两个分别表示现在的操作是还是,优化空间用滚动数组,或者几个 309. Best Time to Buy and Sell Stock with Cooldown 题目链接:https://leetcode.com/problems... dp来解,要用两个dp array分别表示现在的操作是buy还是sell,优化空间用滚动数组,或者几个int public clas...

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

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

    elliott_hu 评论0 收藏0

发表评论

0条评论

FullStackDeveloper

|高级讲师

TA的文章

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