【LeetCode with Python】 Best Time to Buy and Sell Stock II
2008-12-07 13:33
585 查看
博客域名:http://www.xnerv.wang
原题页面:https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
题目类型:数组,贪婪法
难度评价:★★
本文地址:/article/1377538.html
Say you have an array for which the ith element is the price of a given stock on dayi.
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).
一开始还以为是找出序列中的最大值和最小值然后求差,这种错误的想法充分暴露了本人炒股属于把钱往里一丢就再也不管了的类型。其实这题体现的就是一个“低买高买”的贪婪思想,需要找到每一个递增的子序列,从而使利润最大化。
原题页面:https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
题目类型:数组,贪婪法
难度评价:★★
本文地址:/article/1377538.html
Say you have an array for which the ith element is the price of a given stock on dayi.
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).
一开始还以为是找出序列中的最大值和最小值然后求差,这种错误的想法充分暴露了本人炒股属于把钱往里一丢就再也不管了的类型。其实这题体现的就是一个“低买高买”的贪婪思想,需要找到每一个递增的子序列,从而使利润最大化。
class Solution: # @param prices, a list of integer # @return an integer def maxProfit(self, prices): len_prices = len(prices) if len_prices <= 1: return 0 start = prices[0] index = 1 income = 0 total_income = 0 while index < len_prices: cur = prices[index] if cur >= prices[index - 1]: income = cur - start index += 1 if len_prices == index: total_income += income else: total_income += income income = 0 start = cur index += 1 return total_income
相关文章推荐
- 【LeetCode with Python】 Best Time to Buy and Sell Stock
- [python]leetcode(309). Best Time to Buy and Sell Stock with Cooldown
- 【LeetCode从零单刷】Best Time to Buy and Sell Stock I, II, With Cooldown
- [Leetcode][python]Best Time to Buy and Sell Stock I/II/III
- 【LeetCode】【Python题解】Best Time to Buy and Sell Stock II
- [LeetCode]题解(python):122-Best Time to Buy and Sell Stock II
- leetcode 【 Best Time to Buy and Sell Stock II 】python 实现
- Leetcode_best-time-to-buy-and-sell-stock-ii(c++ and python version)
- leetcode_[python/C++]_121/122/123/188.Best Time to Buy and Sell Stock I/II/III/IV
- 【LeetCode with Python】 Best Time to Buy and Sell Stockd
- 【LeetCode】【Python解决问题的方法】Best Time to Buy and Sell Stock II
- [leetcode]Best Time to Buy and Sell Stock II @ Python
- LeetCode 122 Best Time to Buy and Sell Stock II
- Best Time to Buy and Sell Stock II ---- LeetCode
- Leetcode Best Time to Buy and Sell Stock II
- leetcode122---Best Time to Buy and Sell Stock II
- LeetCode 121, 122, 123. Best Time to Buy and Sell Stock i, ii, iii
- [LeetCode] 递推思想的美妙 Best Time to Buy and Sell Stock I, II, III O(n) 解法
- Best Time to Buy and Sell Stock II leetcode java
- LeetCode:Best Time to Buy and Sell Stock with Cooldown