【LeetCode 0122】【DSF/DP/Greedy】买卖股票的最佳时机2

  1. Best Time to Buy and Sell Stock II

You are given an integer array prices where prices[i] is the price of a given stock on the i^th day.

On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day.

Find and return the maximum profit you can achieve.

Example 1:

**Input:** prices = [7,1,5,3,6,4]
**Output:** 7
**Explanation:** Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
Total profit is 4 + 3 = 7.

Example 2:

**Input:** prices = [1,2,3,4,5]
**Output:** 4
**Explanation:** Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Total profit is 4.

Example 3:

**Input:** prices = [7,6,4,3,1]
**Output:** 0
**Explanation:** There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0.

Constraints:

  • 1 <= prices.length <= 3 * 10^4
  • 0 <= prices[i] <= 10^4
Idea
* DSF
* DP
* Greedy
/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function(prices) {
    let res = 0;
    for(let i = 1; i < prices.length; i++){
        if(prices[i-1] < prices[i]){ // 将每天的收益看作自己的收益
            res += prices[i] - prices[i-1]
        }
    }
    return res;
};

相关推荐

  1. leetcode121. 买卖股票最佳时机

    2024-07-12 00:24:02       54 阅读
  2. Leetcode 121 买卖股票最佳时机

    2024-07-12 00:24:02       56 阅读
  3. LeetCode买卖股票最佳时机

    2024-07-12 00:24:02       47 阅读
  4. 买卖股票最佳时机

    2024-07-12 00:24:02       27 阅读
  5. LeetCode-题目整理【3】:买卖股票最佳时机

    2024-07-12 00:24:02       47 阅读
  6. [leetcode]买卖股票最佳时机 (动态规划)

    2024-07-12 00:24:02       48 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-12 00:24:02       66 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-12 00:24:02       70 阅读
  3. 在Django里面运行非项目文件

    2024-07-12 00:24:02       57 阅读
  4. Python语言-面向对象

    2024-07-12 00:24:02       68 阅读

热门阅读

  1. C++ 定时器触发

    2024-07-12 00:24:02       24 阅读
  2. SqlSugar分表笔记

    2024-07-12 00:24:02       25 阅读
  3. 模板语法指令语法——02

    2024-07-12 00:24:02       21 阅读
  4. LeetCode 算法:实现 Trie (前缀树) c++

    2024-07-12 00:24:02       21 阅读
  5. 周报 | 24.7.1-24.7.7文章汇总

    2024-07-12 00:24:02       20 阅读
  6. httpclient访问https请求报错处理

    2024-07-12 00:24:02       19 阅读
  7. 力扣---41. 缺失的第一个正数

    2024-07-12 00:24:02       23 阅读
  8. 微信小程序之使用上拉加载实现图片懒加载

    2024-07-12 00:24:02       24 阅读
  9. C++ --> 类和对象(一)

    2024-07-12 00:24:02       21 阅读
  10. 系统架构的基础:定义、原则与发展历程

    2024-07-12 00:24:02       22 阅读