【leetcode刷题笔记】Best Time to Buy and Sell Stock II

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

解题:简单贪心,如果今天买,明天涨就不卖,如果明天跌就卖掉,如果后天涨明天就又买进来。

代码:

复制代码
 1 class Solution {
 2 public:
 3     int maxProfit(vector<int> &prices) {
 4         int answer = 0;
 5         if(prices.size() == 0)
 6             return 0;
 7         for(int i = 0;i < prices.size()-1;i++)
 8         {
 9             if(prices[i+1]>prices[i])
10                 answer += prices[i+1]-prices[i];
11         }
12         return answer;
13     }
14 };
复制代码

我还问了这个问题:http://oj.leetcode.com/discuss/4082/why-do-i-have-to-add-if-prices-size-0-return-0

Java版本:

复制代码
 1 public class Solution {
 2     public int maxProfit(int[] prices) {
 3         int sum = 0;
 4         for(int i = 0;i < prices.length-1;i++){
 5             if(prices[i+1] > prices[i])
 6                 sum += prices[i+1]-prices[i];
 7         }
 8         return sum;
 9     }
10 }
复制代码

 

posted @   SunshineAtNoon  阅读(216)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示