【牛客题霸题解】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

相关推荐

2025-11-12 14:30
已编辑
广东科技学院 前端工程师
迷茫的小刺猬在迎接o...:前端岗位越来越少了,中小厂也更倾向全栈了,更不需要初级或者实习。可能就大厂才会有一些岗位,但是很看学历。
实习,投递多份简历没人回...
点赞 评论 收藏
分享
评论
25
7
分享

创作者周榜

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