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

思路

这题是121题的续集,这题可以使用任意次交易,所以我们的策略就是低价买,高价卖,在所有的价格谷底买即可。体现到算法上就是,我们的收益是股票上涨的总额。

解答


class Solution {
public:
    int maxProfit(vector<int>& prices) {
        // for weird input
        if (prices.size() == 0) {
            return 0;
        }
        int result = 0;
        for (int i = 0; i < prices.size() - 1; ++i) {
            result += max(0, prices[i + 1] - prices[i]);
        }
        return result;
    }
};

你可能感兴趣的:(C++,leetcode)