LeetCode 122 Best Time to Buy and Sell Stock II(股票买入卖出的最佳时间 II)
来源:互联网 发布:it 域名 编辑:程序博客网 时间:2024/04/27 00:55
题目描述:
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).
解题思路:举一个例子4 9 2 2 8最大利润很明显是 (9-4) + (8 - 2)=11就因为这个式子让我想复杂了:
首先要找到一个极小值4,然后找到极大值9;然后找到极小值2,然后找到极大值8;balabala……其实换一种思路,
(9-4) + (8 - 2) =11这样就转外为后一个比前一个大的话就加入,中间那些不是极大,极小值的会被消去~
C++代码:
class Solution {public: int maxProfit(vector<int>& prices) { int length = prices.size(); //中间的值可以抵消 int num = 0; for(int i = 1;i<length;i++) { if(prices[i]>prices[i-1]) { num+=prices[i]-prices[i-1]; } } return num; }};
python代码:
class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ num = 0 length = len(prices) for i in range(1,length): if prices[i]>prices[i-1]: num = num+prices[i]-prices[i-1] return num
知乎主页:忆臻
专栏地址:机器学习算法
博客地址:忆臻博客
0 0
- LeetCode 122 Best Time to Buy and Sell Stock II(股票买入卖出的最佳时间 II)
- LeetCode 122 Best Time to Buy and Sell Stock II(股票买入卖出的最佳时间 II)
- Best Time to Buy and Sell Stock II 最佳时间买入卖出股票(多次买卖)@LeetCode
- LeetCode 121 Best Time to Buy and Sell Stock(股票买入卖出的最佳时间)
- Best Time to Buy and Sell Stock 最佳时间买入卖出股票(一次买入卖出) @LeetCode
- 最佳时间买入卖出股票 Best Time to Buy and Sell Stock LeetCode
- Best Time to Buy and Sell Stock III 最佳时间买入卖出股票(最多两次买卖)@LeetCode
- 122. Best Time to Buy and Sell Stock II 最佳买卖股票的时间
- LeetCode OJ 之 Best Time to Buy and Sell Stock II (买卖股票的最佳时间 2)
- leetcode 122. Best Time to Buy and Sell Stock II 股票买卖最佳时间(二)
- [LeetCode]122. Best Time to Buy and Sell Stock II(最佳买卖时间 II)
- Best Time to Buy and Sell Stock II 买卖股票最好的时间II
- LeetCode | Best Time to Buy and Sell Stock II(股票购买抛售问题II)
- LeetCode 121. Best Time to Buy and Sell Stock--股票买入后再卖出,求最大收益,最多交易一次
- LeetCode OJ 之 Best Time to Buy and Sell Stock (买卖股票的最佳时间)
- [LeetCode] Best Time to Buy and Sell Stock IV 买卖股票的最佳时间之四
- LeetCode-121-Best Time to Buy and Sell Stock(最佳买卖股票的时间)
- Leetcode 122 Best Time to Buy and Sell Stock II 不限次数买卖股票最大收益
- iOS 沙盒文件路径获取
- Effective Java 读书笔记——39:必要时进行保护性拷贝
- [Leetcode] 73. Set Matrix Zeroes 解题报告
- 区间找点
- CCF201403-2 窗口(100分)
- LeetCode 122 Best Time to Buy and Sell Stock II(股票买入卖出的最佳时间 II)
- 微信自研生产级 Paxos 类库 PhxPaxos 实现原理介绍
- 2 文件处理、权限管理、搜索
- 声明和使用常量
- CCF201312-2 ISBN号码(100分)
- 【9934】选课
- 操作符
- C语言上课笔记:\n与\t
- python 9-4 如何实现属性可修改的函数装饰器,python3 nolocal或者在python2中列表方式