Leetcode best time to Buy and Sell Stock II

Source: Internet
Author: User
Tags diff

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

Problem Solving Ideas:

The subject can be bought and sold many times, but at the same time there can only be one share in hand.
This can be bought before each ascending subsequence and sold at the end of the ascending sub-sequence. Equal to the gain of all ascending sub-sequences.
Also, for a ascending subsequence, such as the 1,2,3,4 sequence in 5,1,2,3,4,0, for two operational scenarios:
One, in 1 to buy, 4 to sell;
Two, buy at 1, 2 sell at the same time buy, 3 sell at the same time buy, 4 sell;
The benefits are the same under both operations.
So the algorithm is: scanning prices from beginning to end, if I is larger than i-1, then price[i]–price[i-1] can be counted into the final revenue. This allows you to scan O (n) for maximum benefit.

This problem can is viewed as finding all ascending sequences. For example, given {5, 1, 2, 3, 4}, buy at 1 & sell at 4 are the same as buy at 1 &sell at 2 & buy at 2& SE LL at 3 & Buy @ 3 & sell at 4.

We can scan the array once, and find all pairs of elements that is in ascending order.

Java Code:

  Public intMaxprofit (int[] prices) {        //This problem can is viewed as finding all ascending sequences.        intProfit = 0;  for(inti = 1; i< prices.length; i++){            intdiff = prices[i]-prices[i-1]; if(diff > 0) {Profit+=diff; }        }        returnprofit; }

Reference:

1. http://www.programcreek.com/2014/02/leetcode-best-time-to-buy-and-sell-stock-ii-java/

2. http://blog.unieagle.net/2012/12/04/leetcode%E9%A2%98%E7%9B%AE%EF%BC%9Abest-time-to-buy-and-sell-stock-ii/

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