Best Time to Buy and Buy Stock II @ LeetCode

Source: Internet
Author: User

Package Level3;/*** Best Time to Buy and keep Stock II *** 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 your transactions as you like (ie, buy one and every one share of the stock multiple times ). however, you may not engage in multiple transactions at the same time (ie, you must wait the s Tock before you buy again ). **/public class S122 {public static void main (String [] args) {int [] prices = {2, 1, 2, 0, 4}; System. out. println (maxProfit (prices);} // greedy method. This question is different from the previous Best Time to Buy and Stock. This question can be used to Buy and Sell stocks multiple times, // to earn the price difference. Therefore, in greedy mode, the basic idea is to lock a low price, and then throw the stock when the price rises to the local highest point // (that is, the price will decrease in the next day, the lower price of the next day is used as a purchase, and then calculated. // Pay attention to the final processing of the final profit public static int maxProfit (int [] prices) {if (prices. length = 0) {return 0;} int totalProfit = 0; int startIndex = 0; int I; for (I = 1; I <prices. length; I ++) {if (prices [I] <prices [I-1]) {totalProfit + = prices [I-1]-prices [startIndex]; startIndex = I ;}} // if (prices [I-1]> prices [startIndex]) {totalProfit + = prices [I-1]-prices [startIndex];} return totalProfit ;}}

 

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.