LeetCode 122 Best Time to Buy and Stock II analysis (the Best Time for buying and selling stocks II)

Source: Internet
Author: User

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;    }};
  

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.