122. Best Time to Buy and Sell Stock(二) leetcode解题笔记

122. Best Time to Buy and Sell Stock II

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).

这一题算是第一题的基础上稍微增加一点难度吧 数组的含义与我上文提到的一致 只是说他不限制你只能买一次了 你可以买任意次  只是在你再次买之前你必须先卖掉你之前买的东西  最终目的还是求最大利润。

这里其实理解了题目的话 解题感觉不难  

可以画一个折线图 这道题的意思就是把所有上坡的地方加起来 粗糙的画个图

每一个红色圈住的地方代表一个小上坡 都已加进去

有了思路 码代码 

public class Solution {
    public int maxProfit(int[] prices) {
        int profit=0;
        for(int i=0;i<prices.length-1;i++){
            int tmp=prices[i+1]-prices[i];
            if(tmp>0){
                profit+=tmp;
            }
        }
        return profit;
    }
}

  一次过 哦也 

空间复杂度o(1)级别  遍历一次时间复杂度0(n)  直接就是最优解了 不用看discuss了 继续看下一题

原文地址:https://www.cnblogs.com/Mrjie/p/6009783.html