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 |