题解 | #买卖股票的最好时机(二),贪心#

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

http://www.nowcoder.com/practice/9e5e3c2603064829b0a0bbfca10594e9

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     * 计算最大收益
     * @param prices int整型一维数组 股票每一天的价格
     * @return int整型
     */
    public int maxProfit (int[] prices) {
        if(prices == null || prices.length < 2) return 0 ;
        int slow = 0 ;//指向买入点
        int fast = 1 ;//寻找卖出最佳点
        int len = prices.length ;
        int maxProfit = 0 ;//最大利益
        while(fast < len) {//思想就是:贪心,每次都是在价格最低点买入,在价格最高点卖出
            if(prices[fast] > prices[fast-1]) {
                fast ++ ;
                if(fast == len) {
                    maxProfit += prices[fast-1] - prices[slow] ;
                }       
            } else {
                maxProfit += prices[fast-1] - prices[slow] ;
                slow = fast ;
                fast ++ ;
            }
        }
        return maxProfit ;
    }
}

一个菜鸟的算法刷题记录 文章被收录于专栏

分享一个菜鸟的成长记录

全部评论

相关推荐

点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务