一天一道LeetCode

本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github

欢迎大家关注我的新浪微博,我的新浪微博

欢迎转载,转载请注明出处

(一)题目

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).

(二)解题

题目大意:相比于上题【一天一道LeetCode】#121. Best Time to Buy and Sell Stock来说,本题有多次买卖的机会。不过,买完之后卖了才能继续买。

解题思路:本题可以采用贪心算法,每次买卖都获取当前的最优值。

思路很简单,每次买卖取得利益最大化,即递增区间,一旦破坏了递增就卖,然后买下一个。遍历完了之后就获得了整体的利益最大化。

具体解释见代码:

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int size = prices.size();
        int max = 0;
        for(int i = 0 ; i < size ; )
        {
            int j = i;
            while(j+1<size&&prices[j+1]>prices[j]) j++;//一旦破坏了递增就停下来
            if(j==i) i++;//一开始就不递增,就直接考虑下一个
            else {
                max+=prices[j]-prices[i];//计算当前最大利润,叠加到全部利润上
                i = j+1;//买下一个
            }
        }
        return max;
    }
};

最新文章

  1. SpringMVC配置项学习笔记
  2. 笔记整理之 Bulk Insert
  3. 微信开发中遇到“当前页面的url未注册”问题
  4. 【转】 js怎么区分出点击的是鼠标左键还是右键?
  5. PHP 数组 foreach引用导致的bug
  6. webform 创建树
  7. [codevs3295]落单的数
  8. sitecustomize.py 用法
  9. javaweb 学习的好地方
  10. 【Web】CGI与Servlet技术对比
  11. cpptoolstip界面提示库使用
  12. 图片转换PDF
  13. webpack4配置详解之常用插件分享
  14. Nginx配置反向代理服务器
  15. 数据挖掘---Numpy的学习
  16. 理解ORM的前提:数据库中的范式和约束
  17. MySQL-mysql 8.0.12安装教程
  18. Xshell 连接 CentOS 7 与 Ubuntu Server
  19. vue2.0 组件化及组件传值
  20. maven 打 fatjar

热门文章

  1. android高德地图网络路径实现自定义marker并点击弹出自定义窗口
  2. 整理spring定时器corn表达式
  3. tf.nn.conv2d 和 tf.nn.max_pool 中 padding 分别为 &#39;VALID&#39; 和 &#39;SAME&#39; 的直觉上的经验和测试代码
  4. GrideSearchCV 优化算法参数
  5. 数据库4m10d作业
  6. 毕业回馈-89c51之定时器/计数器(Timer/Count)
  7. python笔记十五(面向对象及其特性)
  8. PHP MySQL Update
  9. 在web应用中使用Log4j 2
  10. Android开发学习之路--性能优化之布局优化