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

分析:
这是一道典型的动态规划的题目,n件物品总的收益问题可以转化为到第i件物品为止,最大的收益。这样,我们可以分阶段地看这个问题,抓住关键:卖出价一定要比买入价高,且差价最大才进行一次交易。一次交易后,再找下一个最低价买入,最高价卖出,最后求得收益总和,就得到了总的最大收益。

具体步骤:

  • step1:设置一个前指针i,一个后指针j=i+1。
  • step2:当找到prices[j]>prices[i]后,继续往后遍历直到prices[j]达到局部峰值,就把此时的prices[j]作为卖出价卖出,减去之前的最低买入价prices[i]作为这一次交易的收益。
  • step3:把卖出价的下一位j当做下一次寻找新的prices[i+1]>prices[i]的起点,继续找卖出与买入的最大差值。
  • step4:返回sum记录的每一次交易的收入总和。

代码

#include <iostream>
using namespace std;
#include <vector>

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if (prices.empty()) return 0;

        int sum = 0;
        int i = 0;
        while (i < prices.size() - 1){
            int j = i + 1;
            while (prices[j] > prices[j-1] && j < prices.size()) j++;   //价格持续增长则不卖出 
            if (j - 1 > i){     //在价格最高位将物品卖出 
                sum += prices[j-1] - prices[i];     //卖出价-买入价 
            }       
            i = j;      //指针位置移到卖出价的下一位,寻找新的买入和卖出价 
        }
        return sum;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值