90:Best Time to Buy and Sell Stock II

    xiaoxiao2021-03-25  68

    题目: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).

    解析:只需要将所有正的利润相加即可

    // 时间复杂度 O(n),空间复杂度 O(1) class Solution { public: int maxProfit(vector<int>& prices) { if (prices.size() <= 1) return 0; int profit = 0; // 将所有正的利润相加 for (int i = 1; i < nums.size(); ++i) { int diff = nums[i] - nums[i - 1]; if (diff > 0) profit += diff; } return profit; } };
    转载请注明原文地址: https://ju.6miu.com/read-38067.html

    最新回复(0)