Partage de technologie

【LeetCode 0122】【DSF/DP/Greedy】Le meilleur moment pour acheter et vendre des actions 2

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

  1. Meilleur moment pour acheter et vendre des actions II

On vous donne un tableau d'entiers pricesprices[i] est le prix d'une action donnée sur lei^th jour.

Chaque jour, vous pouvez décider d'acheter et/ou de vendre l'action. Vous ne pouvez détenir que au plus un action de l'action à tout moment. Cependant, vous pouvez l'acheter puis la revendre immédiatement sur le marchémême jour.

Trouver et retourner le maximum le profit que vous pouvez réaliser.

Exemple 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.
  • 1
  • 2
  • 3
  • 4
  • 5

Exemple 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.
  • 1
  • 2
  • 3
  • 4

Exemple 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.
  • 1
  • 2
  • 3

Contraintes:

  • 1 <= prices.length <= 3 * 10^4
  • 0 <= prices[i] <= 10^4
Idée
* DSF
* DP
* Greedy
  • 1
  • 2
  • 3
/**
 * @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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13