题解 | #买卖股票的最好时机#

买卖股票的最好时机

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

import java.util.*;

public class Solution {
    /**
     * 
     * @param prices int整型一维数组 
     * @return int整型
     */
    public int maxProfit (int[] prices) {

        if(null == prices || prices.length == 0){
            return 0;
        }

        int bestResult = 0;
        int buyPrice = prices[0];
        for(int i=1;i<prices.length;i++){
            //最便宜的时候买 最高的时候卖 才是最划算的
            //如: [8,1,2,3,4,9] 1块钱买 9块钱卖
            //如: [1,2,3,4,5,9] 1块钱买 9块钱卖
            //如: [8,16,1,1,1]  8块钱买 16块钱卖
            //如: [9,8,7,6,5,4,3,2,1] 应该是1块钱买 1块钱卖
            buyPrice = Math.min(buyPrice,prices[i]);
            bestResult = Math.max(bestResult,prices[i]-buyPrice);
        }

        return bestResult;
    }
}
全部评论

相关推荐

26应届求职ing:你这是报了豆音四哥的班?双非本硕拿这两个项目写简历里投100多家嵌软也没什么面试,感觉项目简单了,很多人用
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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