Leetcode [] [] [simple 122. The best time to buy and sell stocks II] [JavaScript]

Title Description

 

122. The best time to trade stocks II

Given an array, which i-th element is a given stock i-day prices.

Design an algorithm to compute the maximum profit you can get. You can close more deals (buy and sell a stock) as much as possible.

Note: You can not simultaneously involved in multiple transactions (you must sell before buying shares again before the fall).

 

Example 1:

Input: [7,1,5,3,6,4]
Output: 7
Explanation: Day 2 (= 1 stock price), when buying, on day 3 (stock price = 5) when sold, this transaction can profit = 5-1 = 4.
Then, on day 4 (stock price = 3) When buying on day 5 (stock price = 6), when sold, this transaction can profit = 6-3 = 3.


Example 2:

Enter: [1,2,3,4,5]
Output: 4
to explain: (stock price = 1) when buying on Day 1, on Day 5 (stock price = 5), when sold, this Exchange can profit = 5-1 = 4.
  Note that you can not buy stock in a series of 1 and day 2, then after they are sold.
  Because it belongs to the same time involved in multiple transactions, you have to sell the stock before the fall before buying again.


Example 3:

Enter: [7,6,4,3,1]
Output: 0
to explain: In this case, no transaction is completed, the maximum profit is zero.

 

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

 

 

answer:

 

Personal questions are intended to be understood as according to an array, index order, if the latter value is greater than a preceding value, there are profits, it is reduced to a large, accumulated into a variable Profit, and finally returns Profit;

 

/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function(prices) {
    if(prices.length === 0)return 0
    let profit = 0
   for(let i = 1; i<prices.length; i++){ if(prices[i]>prices[i-1]){ profit += prices[i] - prices[i-1] } } return profit };

 

 

 

Guess you like

Origin www.cnblogs.com/2463901520-sunda/p/11450691.html