best time to Buy and Sell Stock II

Source: Internet
Author: User

best time to Buy and Sell Stock II

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).

The problem begins to not understand the meaning is to give you an array, the first element of the I-day stock price, you can buy and sell multiple stocks in this array, but only one stock, such as 5,0,1,2,3,4 you can buy 0 sold 0 Then buy 1, sold 1 and then buy 2 ...

This problem uses a greedy algorithm, refer to http://blog.unieagle.net/2012/12/04/leetcode%E9%A2%98%E7%9B%AE%EF%BC%9Abest-time-to-buy-and-sell-stock-ii/

Buy it the day before, and sell it on a daily, if you earn money, add it to pro, and finally return pro

1  Public classSolution {2      Public intMaxprofit (int[] prices) {3         intPro = 0;4          for(inti = 1; i < prices.length; i++){5             if(Prices[i]-prices[i-1] > 0)6Pro = Pro + Prices[i]-prices[i-1];7         }8         9         returnPro;Ten     } One}

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.