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

买卖股票的最好时机

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

import java.util.*;


public class Solution {
    /**
     * 
     * @param prices int整型一维数组 
     * @return int整型
     */
    public int maxProfit (int[] prices) {
        // write code here
        int length = prices.length;
        //空数组处理
        if(length == 0 || length == 1){
            return 0;
        }
        
        int[] dp = new int[length];
        int max = 0;
        int min = prices[0];
        int tempMax = 0;
        /**
            遍历数组,将新遍历得到的数(prices[i])与该数前面的的数组中最小数(min)相减,便可得到临时最大收益值(tempMax),
            再将该值与当前最大收益值相比较(max),更新当前最大收益值相比较
        */
        for(int i = 1;i<length;i++){
            tempMax = prices[i] - min;
            //更新temp值
            if(tempMax > max){
                max = tempMax;
            }
            
            //更新min值
            if(prices[i]<min){
                min = prices[i];
            }
        }
        
        return max;
    }
}
全部评论

相关推荐

05-23 20:31
已编辑
武汉大学 Java
内向的柠檬精在研究求职打法:注意把武大标粗标大 本地你俩不是乱杀
点赞 评论 收藏
分享
鬼迹人途:你去投一投尚游游戏,服务器一面,第一个图算法,做完了给你一个策略题,你给出方案他就提出低概率问题,答不上当场给你挂
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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