【牛客题霸题解】NC7 股票(一次交易)

买卖股票的最好时机

http://www.nowcoder.com/questionTerminal/64b4262d4e6d4f6181cd45446a5821ec

因为只能买卖一次,我们把每一天都看一遍,如果在当天卖出的话能获得的最大收益是多少,然后再取最大值,就是答案了。
在某一天卖出的最大收益的条件是:在这一天之前价格最便宜的时候买
c++

class Solution {
public:
    int maxProfit(vector<int>& prices) {
            int minn = prices[0];
            int ans = 0;
            for(int i = 0 ; i < prices.size() ; i++)
            {
                    minn = min(minn,prices[i]);
                    ans = max(ans,prices[i]-minn);
            }
            return ans;
    }
};

java

import java.util.*;
public class Solution {
    public int maxProfit (int[] prices) {
        int minn = prices[0];
        int ans = 0;
        for(int i = 0 ; i < prices.length ; i++)
        {
            minn = Math.min(minn,prices[i]);
            ans = Math.max(ans,prices[i]-minn);
        }
        return ans;
    }
}

python

class Solution:
    def maxProfit(self , prices ):
        # write code here
        minn = prices[0];
        ans = 0;
        for i in range(0,len(prices)):
            minn = min(minn,prices[i]);
            ans = max(ans,prices[i]-minn);
        return ans;
牛客题霸题解 文章被收录于专栏

QAQ

全部评论
做也能做出来,但思想是真没这么简洁
点赞 回复 分享
发布于 2021-03-19 15:27
yyds!
点赞 回复 分享
发布于 2020-12-29 16:09

相关推荐

不知道怎么取名字_:愚人节收到的吧,刚看到有人也是愚人节说收到offer的
腾讯求职进展汇总
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
03-15 10:59
已编辑
爱写代码的菜code...:哎,自己当时拿到字节offer的时候也在感叹终于拿到了,自己当时最想去的企业就是字节,结果还是阴差阳错去了鹅厂。祝uu一切顺利!!!
点赞 评论 收藏
分享
评论
25
7
分享

创作者周榜

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