题解 | 买卖股票的最好时机(二) 给问题建模 一步一步抽丝剥茧 可以得到极简的代码

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

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

class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 计算最大收益
     * @param prices int整型vector 股票每一天的价格
     * @return int整型
     */
    int maxProfit(vector<int>& prices) {
        // write code here
        int size=prices.size();
        if(size<2)return 0;
        int res=0;
        for(int i=1;i<size;i++){
            if((prices[i]-prices[i-1])>0)res+=prices[i]-prices[i-1];
        }
        //非常优雅的代码 但也很残忍 没额外存储任何信息 只得到了最大收益
        return res;
    }
};

全部评论
点赞 回复 分享
发布于 04-30 17:56 河南

相关推荐

评论
点赞
收藏
分享

创作者周榜

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