1.题目:
Say you have an array for which the i th 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).
2.思路
这道题由于可以无限次买入和卖出。我们都知道炒股想挣钱当然是低价买入高价抛出,那么这里我们只需要从第二天开始,如果当前价格比之前价格高,则把差值加入利润中,因为我们可以昨天买入,今日卖出,若明日价更高的话,还可以今日买入,明日再抛出。以此类推,遍历完整个数组后即可求得最大利润
3.代码:
普通的for循环 存在问题 就是prices的length以及i++后数组溢出;改成length-1 先++i的for循环即可解决;
public class Solution { public int maxProfit(int[] prices) { //可以直接计算每天的差价 int profit = 0; for(int i = 0;i< prices.length - 1; ++i){ int dis = prices[i+1]-prices[i]; if(dis>0){ profit+=dis; } } return profit; } }============================
这个题目还有一个通过率更低的扩展题:
1.题目:
Say you have an array for which the i th element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
2.思路:
这种题目,实现的思路很多,这个主要就是判空,需要注意;然后直接用for循环,边找最小边计算差值最大的。
3.代码:
public class Solution { public int maxProfit(int[] prices) { if(prices == null || prices.length == 0){ return 0; } int res = 0; int min = prices[0]; for(int i = 0;i< prices.length;i++){ if(min > prices[i]){ min = prices[i]; } else{ res = Math.max(prices[i]-min,res); } } return res; } }