best time to Buy and Sell Stock II
Problem:
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).
Ideas:
Increase in the process of accumulation can
My Code:
Public classSolution { Public intMaxprofit (int[] prices) { intLen =prices.length; if(Len <= 1) return0 ; intProfit = 0 ; for(inti = 0; i < len-1; i + +) { if(Prices[i+1] >Prices[i]) profit+ = prices[i+1]-Prices[i]; } returnprofit; }}
View Code
Others code:
Public classSolution { Public intMaxprofit (int[] prices) { intProfit = 0; for(inti = 0; i < prices.length-1; i++) { intdiff = prices[i+1]-Prices[i]; if(diff > 0) {Profit+=diff; } } returnprofit; }}
View Code
The Learning Place:
Diff variable name is good
best time to Buy and Sell Stock II