题目如下:
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;
}
}
由于交易次数不限,只要当天价格比前一天高,就进行交易。,这样便可保证收益最大,可使用贪心的思路解决。
网友评论