Leetcode OJ 122. best time to Buy and Sell Stock II

Source: Internet
Author: User

Say you has an array for which the i-th element is the price of a given-stock on day I.

Design an algorithm to find the maximum profit. You could complete as many transactions as (ie, buy one and sell one share of the stock multiple times). However, engage in multiple transactions for the same time (ie, you must sell the stock before you buy again).

Ideas

Compared to the previous topic, this topic relaxes the trade limit, can do a long trade, but before the next transaction must complete the previous transaction, and the same transaction can only be done once. My train of thought is: If the price rises in the future, then I will buy at the moment. If the price falls in the future, I will sell it at the moment. The result is dividing the array into an ascending sequence of segments, buying at the very beginning of the sequence, and finally selling. For example: [2,1,25,4,5,6,7,2,4,5,1,5]. The array is divided into 5 increments, in the first sequence the profit is 0, the second series profit is 24, the third is 3, the fourth is 3, and the fifth is 4. The total profit is 34. The code is as follows:

1  Public classSolution {2      Public intMaxprofit (int[] prices) {3         intMin = 0;4         intSump = 0;5         intMP = 0;6 7          for(inti = 1; i < prices.length; i++) {8             if(Prices[i] < prices[i-1]){9Sump = Sump +MP;TenMin =i; OneMP = 0; A             } -             Else -MP = Prices[i]-Prices[min]; the         } -  -         returnSump +MP; -     } +}

Leetcode OJ 122. best time to Buy and Sell Stock II

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.