题解 | #买卖股票的最好时机(二)#

买卖股票的最好时机(二)

https://www.nowcoder.com/practice/9e5e3c2603064829b0a0bbfca10594e9

/** state translat equation
f(0) = 0
f(x) = f(x-1) if v(x-1) > v(x)
f(x) = f(x-2) + v(x) - v(x-2) if v(x-1) < v(x) && left 0
f(x) = f(x-1) + v(x) - v(x-1) if v(x-1) < v(x) && left 1
*/

/**
* only need to save f(x) and f(x-1)
*/

#include <algorithm>
#include <cerrno>
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     * 计算最大收益
     * @param prices int整型vector 股票每一天的价格
     * @return int整型
     */
    int maxProfit(vector<int>& prices) {
        // write code here
        // vector<int> maxProfit(prices.size(), 0);
        int maxProfit, maxProfit_pre;
        bool bLeft = true;
        for(auto i=1; i < prices.size(); i++) {
            if(prices[i] > prices[i-1]) {
                if(bLeft) {
                    maxProfit_pre = maxProfit;
                    maxProfit = maxProfit + prices[i] - prices[i-1];
                } else {
                    int tmp = maxProfit;
                    maxProfit = maxProfit_pre + prices[i] - prices[i-2];
                    maxProfit_pre = tmp;
                }
                bLeft = false;
            } else {
                maxProfit_pre = maxProfit;
                bLeft = true;
            }
        }
        return maxProfit;
    }
};

全部评论

相关推荐

06-16 15:04
黑龙江大学 Java
零OFFER战士:另一个版本查看图片
点赞 评论 收藏
分享
门口唉提是地铁杀:之前b站被一个游戏demo深深的吸引了。看up主页发现是个初创公司,而且还在招人,也是一天60。二面的时候要我做一个登录验证和传输文件两个微服务,做完要我推到github仓库,还要我加上jaeger和一堆运维工具做性能测试并且面试的时候投屏演示。我傻乎乎的做完以后人家跟我说一句现在暂时不招人,1分钱没拿到全是白干
你的秋招第一场笔试是哪家
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务