贪心算法,只要后一天的价格大于前一天的价格就买入。
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;
}
};