This article is in the study summary, welcome reprint but please indicate the origin: http://blog.csdn.net/pistolove/article/details/43155725
Say you have an array for which the ith element are the price of a given the
Design a algorithm to find the maximum profit. You may complete as many transactions as (ie, buy one and sell one share of the stock multiple times). However, you could not engage in multiple transactions at the same time (ie, your must sell the stock before your buy again).
Ideas:
(1) for given an array, the value of the first element of the array corresponds to the first day of the stock, you can complete many transactions, but each transaction can only buy once and sell, for multiple exchanges can get the maximum profit. The enhanced edition of the title "best time to Buy and Sell".
(2) similar to the Sell stock, the maximum difference is also examined in the same question. It only examines the sum of the differences in the values of all adjacent and incremental elements in the array. As long as the value of the first I+1 day is greater than the value of day I, then you can buy, get profit (margin), traverse the entire array, obtain the sum of the difference between the sum is the total profit.
(3) The problem is relatively simple. I hope it will be of some help to you.
The algorithm code is implemented as follows:
/**
*
* @author liqq
/public int maxprofit (int[] x) {
if (x = null | | x.length <= 1)
return 0;
int min = x[0];
int profit = 0;
for (int i = 0; i < x.length i++) {
if (min > X[i]) {
min = x[i];
} else {
Profit = x[i]-min ;
min = X[i];
}
return profit;
}