題目如下:
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).
我的提交:
//17.3.27
//貪心
public class Solution {
public int maxProfit(int[] prices) {
int n = prices.length;
int profit = 0;
for(int i=1;i<n;i++){
if(prices[i]-prices[i-1]>0)
profit += prices[i]-prices[i-1];
}
return profit;
}
}
由于交易次數(shù)不限魁巩,只要當(dāng)天價格比前一天高,就進行交易姐浮。谷遂,這樣便可保證收益最大,可使用貪心的思路解決卖鲤。