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

接口:

class Solution {
public:
    /**
     * @param prices: Given an integer array
     * @return: Maximum profit
     */
    int maxProfit(vector<int> &prices) {
        // write your code here

    }
};

分析:

这道题目实际上不是让你维护一个最大值,而是求profit得和。很明显的,每次股票上涨你都买卖,最后求和就能得到最大利润。

需要注意的一点是,当连续两天上涨的时候,利润依然等于(p[2] - p[1]) + (p[3] - p[2])。也就是如果你在p[2]不出手,和卖出再买入,是一回事儿!

解法:

class Solution {
public:
    /**
     * @param prices: Given an integer array
     * @return: Maximum profit
     */
    int maxProfit(vector<int> &prices) {
        // write your code here
        if (prices.size() <= 1) {
            return 0;
        }

        int maxProfit = 0;
        for (int i = 0; i < prices.size() - 1; i++) {
            if (prices[i + 1] > prices[i]) {
                maxProfit += prices[i + 1] - prices[i];
            }
        }

        return maxProfit;
    }
};

results matching ""

    No results matching ""