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


1:注意特殊情况;2:找到数组相邻的凹点和凸点;3:两者的差值是当前的最大值。4:在查找凸凹值的时候注意边界


    int maxProfit(vector<int> &prices)
    {
        if(prices.size() <= 1)
        {
            return 0;
        }
        
        int maxValue = 0;
        int start = 0;
        int end = 0;
        int size = (int)prices.size();
        
        while(start < size)
        {
            while(start < size - 1 && prices[start] >= prices[start + 1])
            {
                start++;
            }
            
            end = start + 1;
            while(end < size - 1 && prices[end] <= prices[end + 1])
            {
                end++;
            }
            
            if(end == size)
            {
                break;
            }
            else
            {
                maxValue += prices[end] - prices[start];
            }
            
            start = end + 1;
        }
        
        
        return maxValue;
    }


原文地址:https://www.cnblogs.com/gcczhongduan/p/5197858.html