LeetCode 122 Best Time to Buy and Sell Stock II

来源:互联网 发布:session php注册示例 编辑:程序博客网 时间:2024/06/05 02:55

题目:

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

题目链接

题意:

给一个数组prices,其中的每一个元素代表一天股票的价格,买与卖都是这个价,第i个元素代表第i天的价格,问经过一定规划后,可是收益最大,最大利益是多少?

要求:

  1. 在一天之内只允许单个操作。
  2. 只允许单买和单卖,当手里有股票未卖掉,不许买新的股票。
分析:
对于给定的一个数组而言,每天价格是多少是已知的,同时,收益等于卖出的价格减去买入的价格,所以可以通过分析数据得出:
  1. 当 prices[i] <= prices[i + 1] 时,可以选择观望,等待至第 i + 1 天。
  2. 当 prices[i] > prices[i + 1] 时,选择卖出股票。
这个问题也就变成了上升子序列的变形题目。求出每个上升子序列的首位之差,并进行求和。
代码如下:
class Solution {public:    int maxProfit(vector<int>& prices) {        int ans = 0;        for (int i = 0; i + 1 < prices.size(); i++) {            if (prices[i] < prices[i + 1]) {                ans -= prices[i];                while (i+1 < prices.size() && prices[i+1] > prices[i]) i++;                ans += prices[i];            }        }        return ans;    }};


原创粉丝点击