您的位置:首页 > 其它

[LeetCode]122 Best Time to Buy and Sell Stock II

2015-01-06 17:50 447 查看
https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
http://blog.csdn.net/linhuanmars/article/details/23164149
public class Solution {

public int maxProfit(int[] prices) {

// If as many transactions
// Gready

int pro = 0;
int buy = 0;
boolean hold = false;

int len = prices.length;

for (int i = 0 ; i < len ; i ++)
{
if (!hold)
{
// Find the next buy day
if (i + 1 < len && prices[i + 1] > prices[i])
{
buy = prices[i];
hold = true;
}
}
else
{
// Find the next sell day
if ((i == len - 1) || // Last day, sell whatever we have
(i + 1 < len && prices[i + 1] < prices[i])) // A good sell day.
{
pro += prices[i] - buy;
hold = false;
}
}
}

return pro;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode