leetcode笔记:Best Time to Buy and Sell Stock II
2015-11-12 00:10
525 查看
一. 题目描述
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).
二. 题目分析
该题是买卖股票的第二题。题目给出的基本信息没什么变化,与第一题不同的是的,允许进行任意次数的买卖,但必须保证买卖一次后才能进行第二次操作。继续分析会发现,这实际上是求股价数组所有上升段的和。
三. 示例代码
四. 小结
与该题相关的题目还有好几道。后续更新…
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 <iostream> #include <vector> using namespace std; class Solution { public: int maxProfit(vector<int> &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; } };
四. 小结
与该题相关的题目还有好几道。后续更新…
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- 动易2006序列号破解算法公布
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#冒泡法排序算法实例分析
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C++联合体转换成C#结构的实现方法
- C#实现的算24点游戏算法实例分析
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析