您的位置:首页 > 其它

LintCode:买卖股票的最佳时机 II

2016-05-10 18:24 459 查看
LintCode:买卖股票的最佳时机 II

贪心算法,只要后一天的价格大于前一天的价格就买入。

Python

class Solution:
"""
@param prices: Given an integer array
@return: Maximum profit
"""
def maxProfit(self, prices):
# write your code here
max_money = 0
for i in range(len(prices)-1):
if prices[i+1] > prices[i]:
max_money += prices[i+1] - prices[i]
return max_money


Java

class Solution {
/**
* @param prices: Given an integer array
* @return: Maximum profit
*/
public int maxProfit(int[] prices) {
// write your code here
int maxMoney = 0;
for(int i=0; i<prices.length-1; i++){
if(prices[i+1] > prices[i]){
maxMoney += prices[i+1] - prices[i];
}
}
return maxMoney;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法