设为首页 加入收藏

TOP

leetcode笔记:Best Time to Buy and Sell Stock II
2015-11-21 00:54:29 来源: 作者: 【 】 浏览:1
Tags:leetcode 笔记 Best Time Buy and Sell Stock

一. 题目描述

Say you have an array for which the i-th 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).

二. 题目分析

该题是买卖股票的第二题。题目给出的基本信息没什么变化,与第一题不同的是的,允许进行任意次数的买卖,但必须保证买卖一次后才能进行第二次操作。继续分析会发现,这实际上是求股价数组所有上升段的和。

三. 示例代码

#include 
   
     #include 
    
      using namespace std; class Solution { public: int maxProfit(vector
     
       &prices) { int result = 0; int i = 0; int len = prices.size(); if(len <= 1) return 0; for(i = 1; i < len; ++i) { if (prices[i] > prices[i - 1]) result += prices[i]-prices[i - 1]; } return result; } };
     
    
   

四. 小结

与该题相关的题目还有好几道。后续更新…

?

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇leetcode笔记:Best Time to Buy .. 下一篇[并发并行]_[线程同步]_[C/C++实..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: