122. Best Time to Buy and Sell Stock II
原题链接:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/
股票最大利润的第二题!
/**
* Created by clearbug on 2018/2/26.
*/
public class Solution {
public static void main(String[] args) {
Solution s = new Solution();
System.out.println(s.maxProfit1(new int[]{7, 1, 5, 3, 6, 4}));
System.out.println(s.maxProfit1(new int[]{7, 1, 5, 8, 10, 4}));
}
/**
* 方法一:这道题目不想第一道那么简单了,所以我思考了两分钟毫无头绪!
* 然后看了讨论区排行第一的帖子,我初看以为答案是错误的,都理解不了,后来发现画出折线图之后才看出其中的精妙之处啊!
* 然后我只想说真他么的六啊!
*
* 时间复杂度:O(n)
*
* @param prices
* @return
*/
public int maxProfit1(int[] prices) {
int total = 0;
for (int i=0; i< prices.length-1; i++) {
if (prices[i+1]>prices[i]) total += prices[i+1]-prices[i];
}
return total;
}
// 官方方法一:暴力递归的方法,效率低下,代码复杂,不太好理解!
// 官方方法二:通过在折线图上找山谷和山峰的方法来解决,稍微简介点了
// 官方方法三:是在官方方法二的基础上进行了简化得来的,其实就他么是上面👆写的方法一而已!
}

浙公网安备 33010602011771号