LeetCode 122 Best Time to Buy and Stock II analysis (the Best Time for buying and selling stocks II)
Translation
In other words, you have an array where the I element represents the stock price for the I day. Design an algorithm to find the maximum profit. You can make as many transactions as possible (for example, buying and selling stocks multiple times ). However, you cannot make multiple transactions at the same time. (For example, you must sell it before the next purchase ).
Original
Say you have an array for which the ith element is the price of a given stock on day i.Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
Analysis
It's actually a very simple question. It's complicated at first ......
Example:
// 4 7 8 2 8 the biggest profit is obviously (8-4) + (8-2) = 10. This formula makes me think complicated: first, find a minimum value of 4, then find the maximum value of 8, then find the minimum value of 2, and then find the maximum value of 8; balabala ...... In fact, in another way, the difference between (7-4) + (8-7) + (8-2) is that you can simply subtract the last number from the previous one, however, if the last number is smaller than the previous one, it is not considered.
Code
class Solution {public: int maxProfit(vector
& prices) { size_t size = prices.size(); if (size <= 1) return 0; int max = 0; for (int i = 1; i < size; ++i) max += prices[i] > prices[i - 1] ? prices[i] - prices[i - 1] : 0; return max; }};