华为机试:最大股票收益

题目来源

题目描述

在这里插入图片描述

题目解析

这道题目和leetcode:122. 买卖股票的最佳时机 II(买卖无限次)几乎一模一样,只要我们首先把价格算出来即可



class Solution{
    std::vector<std::string> split(std::string &str, char ch){
        std::vector<std::string> ans;
        str += ch;
        int i = 0;
        for (int j = 0; j < str.size(); ++j) {
            if(str[j] == ch){
                ans.push_back(str.substr(i, j - i));
                i = j + 1;
            }
        }
        return ans;
    }

    int maxPrices(std::vector<int> &prices){
        int N = prices.size();
        std::vector<int> have(N, 0);
        std::vector<int> no(N, 0);
        have[0] = - prices[0];
        no[0] = 0;
        for (int i = 1; i < N; ++i) {
            have[i] = std::max(have[i - 1], no[i - 1] - prices[i]);
            no[i] = std::max(no[i], have[i - 1] + prices[i]); // 昨天持有时最大收益 + 今天卖出得到的钱
        }

        return no.back();
    }
public:
    int process(std::string str){
        auto tmp = split(str, ' ');
        std::vector<int> prices;
        for (auto & i : tmp) {
            if(i.back() == 'Y'){
                prices.push_back(strtol(i.c_str(), NULL, 10));
            }else{
                prices.push_back(7 * strtol(i.c_str(), NULL, 10));
            }
        }

        return maxPrices(prices);
    }
};


int main() {
    std::string str;
    getline(std::cin, str);
    Solution a;
    std::cout << a.process(str);
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值