题解 | #买卖股票的最好时机(二)# [P2]

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

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

lastP记录目前为止看到的最低开仓价格
只要第i天的价格比lastP高,就获利了结
import java.util.*;

public class Solution {
    public int maxProfit (int[] prices) {
      if (prices.length <= 1) return 0;
      int lastP = Integer.MAX_VALUE;
      int profit = 0;
      
      for (int p : prices) {
        if (p > lastP) 
          profit += p - lastP;
        lastP = p;
      }
      return profit;
    }
}
DP是真的烦 文章被收录于专栏

只是为了把DP的题集中一下方便自己复习

全部评论

相关推荐

07-15 11:35
门头沟学院 Java
心里踏实多了,可以安心准备论文了
看不见我ffgh:牛哇佬,要不要来试一试pdd,部门氛围很好
京东开奖153人在聊
点赞 评论 收藏
分享
06-26 15:33
青岛工学院 Java
积极的秋田犬要冲国企:他现在邀请我明天面试
点赞 评论 收藏
分享
07-15 18:09
门头沟学院 Java
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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