[LeetCode] 122. Best Time to Buy and Sell Stock II

题目链接:传送门

Description

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

Solution

题意:

给定 n 天的股票价格,可以进行多次交易,但同一时刻不能进行多个交易,即在买股票之前要将手中的股票先卖出去,问最大收益

思路:

被这题卡了有点时间...

注意理解题面中

you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again)

一开始没转过来,以为是选若干个不相交的线段,求这些线段差值和的最值

但是仔细想想,股票是可以在同一天卖出和买入的,关键就在于此

由于股票可以在同一天卖出和买入,那么显然可以将一个区间 \([L, R]\) 分为一个个小区间 \([L, L+1], [L+1, L+2], ..., [R-1, R]\)

通俗的理解就是 在 L 这天买入, R 这天卖出,相当于在 L 这天买入,L+1 这天卖出,再在 L+1 这天买入,...,在 R-1 这天买入,R 这天卖出

这样子就很明显了,处理每一个小区间即可。

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int res = 0;
        for (int i = 1; i < prices.size(); i++)  res += max(0, prices[i] - prices[i - 1]);
        return res;
    }
};
posted @ 2018-02-28 01:38  酒晓语令  阅读(91)  评论(0编辑  收藏  举报