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

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

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

对每天的价格: 保存一个之前的最小价格 保留一个之前的最大收益

import java.util.*;


public class Solution {
    public int maxProfit (int[] prices) {
        // write code here
        if(prices == null || prices.length == 0){
            return 0;
        }
        int len = prices.length;
        //每天与之前最小价格的差值
        int[] dp = new int[len];
        //最小价格
        int min = prices[0];
        //最大收益
        int max = 0;
        for(int i = 1; i < len; i++){
            dp[i] = prices[i] - min;
            min = Math.min(min,prices[i]);
            max = Math.max(max,dp[i]);
        }
        return max;
    }
}
全部评论

相关推荐

用微笑面对困难:只要你保证项目和获奖都是真的就行尤其是“对战,总负责人”啊这些套职,基本上队员,打杂的都这么写
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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