LeetCode刷题实战122:买卖股票的最佳时机 II
共 1542字,需浏览 4分钟
·
2020-12-16 21:16
Say you have an array prices 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 (i.e., buy one and sell one share of the stock multiple times).
Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).
题意
解题
本题和上一题相比,唯一的区别是:这里对买卖次数没有限制。
public int maxProfit(int[] prices) {
//贪心法
if(prices==null || prices.length==0)
return 0;
int profit=0;
for(int i=1;iif(prices[i]>prices[i-1])
profit+=(prices[i]-prices[i-1]);
}
return profit;
}