Best Time to Buy and Sell Stock II(leetcode)

Best Time to Buy and Sell Stock II


题目

leetcode题目

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


解决

简单的想法是今天买,明天卖。
如果今天比昨天获利,则卖出股票,再次买进股票;若今天比昨天亏损,则不进行任何操作。

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int result = 0;
        int num = prices.size();
        for (int i = 1; i < num; i++) {
            result += (prices[i] - prices[i - 1] > 0) ? prices[i] - prices[i - 1] : 0;
        }
        return result;
    }
};

猜你喜欢

转载自blog.csdn.net/joker_yy/article/details/78843539