1 解题思想
首先请看下第一个问题:
Leetcode 121. Best Time to Buy and Sell Stock 股票买卖 解题报告
题目给定的数组还是一样的含义,依旧代表股票的价格,但是现在不同的是,现在你可以任意次数的买卖(当然还是要先买后卖才行,不能买两次再卖等)
这道题目我的解法很naive,在第i天,只要第i+1天的售价高于第i天,那么我就买,然后i+1天卖了。
关于其中原理,可以认为是,我们这样做,赶上了所有可以赚钱的机会,且没有误入一个赔钱的机会。
可以理解为我们求得了(类似倒数)的每天利润差,我们赶上了所有增长的地方,所以肯定是最大的
2 原题
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).
Subscribe to see which companies asked this question
3 AC解
public class Solution {
/**
* 其实就是一个股票问题,同一个时间可以随时买卖,所以只要后一个比前一个多,那就可以买了
* */
public int maxProfit(int[] prices) {
int result=0;
for(int i=1;i<prices.length;i++){
if(prices[i]-prices[i-1]>0)
result+=(prices[i]-prices[i-1]);
}
return result;
}
}