Best time to buy and buy stock |

Source: Internet
Author: User

Say you have an array for whichITh element is the price of a given stock on dayI.

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 stock before you buy again ).

First, I understand the meaning of the question: the question description can be bought and sold multiple times, but only one at a time can be in the hand. One day you can sell the stock and then buy it, using the greedy idea:
In this way, you can buy before each ascending subsequence and sell at the end of the ascending subsequence. It is equivalent to obtaining the benefits of all ascending subsequences.
Furthermore, for a ascending subsequence, such as the 1, 2, 3, and 4 sequences in, there are two operation schemes:
1. Buy at 1 and sell at 4;
2. Buy at 1, 2 at the same time, 3 at the same time, and 4 at the same time;
With simple mathematical operations, we can find that the benefits of these two operations are the same.

public class Solution {    public int maxProfit(int[] prices) {        if(prices.length==0){        return 0;        }        int MaxProfit = 0;        int len = prices.length;        for(int i=1;i<len;i++){        if(prices[i]>prices[i-1]){        MaxProfit+= prices[i]-prices[i-1];        }        }        return MaxProfit;    }}




 

Best time to buy and buy stock |

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.