题解 | #买卖股票的最好时机(二)# [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的题集中一下方便自己复习

全部评论

相关推荐

代码飞升:别用口语,后端就写后端,前端就写前端,最后别光后悔
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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