LeetCode 122: Best Time to Buy and Sell Stock 2 解题与思考

LeetCode 122: Best Time to Buy and Sell Stock 2 解题与思考

[原题链接]

题目描述

相比上一道题,这次你可以买很多次,但是你每次最多只能持有一只股票:你在抛出上一只股票之前无法买下一只。求最大利润

思路

一旦即将降价就抛售,即将升价就买入,没什么好说的

算法

顺序遍历数组,记录一下是否上升下降,是否需要买入卖出

代码

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


class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if ( prices.size() == 0 ) return 0;
        int P = 0, last = prices[0];
        bool isRising = (prices[0] > prices[1]) ? false : true;
        for ( auto i = prices.begin(); i != prices.end(); i++ ) {
            if ( isRising ) {
                if ( i + 1 == prices.end() )P += *i- last;
                else {
                    if ( *i > *(i + 1) ) {
                        P += *i - last;
                        isRising = false;
                    }
                }
            }
            else {
                if ( i + 1 == prices.end() );
                else {
                    if ( *i < *(i + 1) ) {
                        last = *i;
                        isRising = true;
                    }
                }
            }
        }
        return P;
    }
};

思考

同样是一道easy,因为是一个系列顺带打完它

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值