[30 day leetcoding challenge] day 5


Hi, everyone. I’m a pig. Welcome to “baby can understand” series special – 30 day leetcoding challenge.

This is an official leetcode event. As you can see on the official website, from April 1, every day, the official will select a question and complete it within 24 hours to get a small reward. Although the reward doesn’t seem to work, as an official punch in activity, piggy still comes to punch the card, which is just for entertainment after work and home every day.

This is the question on April 5, and the 122 item in the list of questions – “the best time to buy and sell stocks II.”

Title Description

Given an array, its I th element is the price of a given stock on day I.

Design an algorithm to calculate the maximum profit you can make. You can do as many trades as you can.

Note: you cannot participate in more than one transaction at the same time (you must sell the previous stock before buying again).

Example 1:

Input: [7,1,5,3,6,4]
Output: 7
Explanation: if you buy on day 2 (stock price = 1) and sell on day 3 (stock price = 5), the exchange can make a profit = 5-1 = 4.
     Then, buy on day 4 (stock price = 3) and sell on day 5 (stock price = 6), the exchange can make a profit = 6-3 = 3.

Example 2:

Input: [1,2,3,4,5]
Output: 4
Explanation: if you buy on day 1 (stock price = 1) and sell on day 5 (stock price = 5), the exchange can make a profit = 5-1 = 4.
     Note that you can't buy shares one day after another and sell them later.
     Because this is involved in multiple transactions at the same time, you have to sell the previous stock before buying again.

Example 3:

Input: [7,6,4,3,1]
Output: 0
Explanation: in this case, the transaction is not completed, so the maximum profit is 0.

Official difficulty



Since there is no requirement for the number of execution of buy and sell, and we have the price data of the whole time period, there is nothing to analyze. Our optimal strategy is very direct – sell high and buy low.

Direct scheme

Think of the line of price points as a discount. We only need to sum the price differences of all segments with positive slope. The specific codes are as follows:

const maxProfit = prices => {
  let profit = 0;
  for (let i = 1; i < prices.length; ++i) {
    const val = prices[i] - prices[i - 1];
    val > 0 && (profit += val);
  return profit;

Of course, we can also write it in one line:

const maxProfit = prices => prices.reduce((prev, cur, curIdx) => cur - prices[curIdx - 1] > 0 ? prev + cur - prices[curIdx - 1] : prev, 0);


As the fifth question of “30 day leetcoding challenge”… Ahhhh, I can’t do it anymore… Please don’t do this officially! Piggy really don’t know what to write, not a drop left!!

I hope I can help you in need… If you think it’s good, remember “Sanlian”. Piggy loves you~

Related links

  • Activity topic list
  • Repo for leetcode
  • My segment fault column
  • My Zhihu column

[30 day leetcoding challenge] day 5