标签:eve gray ted class head cal vertica san like
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
public class Solution {
public int MaxProfit(int[] prices) {
int sum = 0;
for (int tail = prices.Length - 1; tail >= 0;)
{
int head = tail -1;
while (head > 0 && prices[head] < prices[head + 1] && prices[head] > prices[head-1])
{
head--;
}
if (head >= 0)
{
int diff = prices[tail] - prices[head];
if (diff > 0)
{
sum += diff;
}
}
tail = head;
}
return sum;
}
}
122. 买卖股票 求最大收益2 Best Time to Buy and Sell Stock II
标签:eve gray ted class head cal vertica san like
原文地址:http://www.cnblogs.com/xiejunzhao/p/b53431464214c560eb29132fb4f2a1fa.html