Question:
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 your transactions as you like (ie, buy one and every one share of the stock multiple times ). however, you may not engage in multiple transactions at the same time (ie, you must wait the stock before you buy again ).
I have been busy from the weekend to work days, but I still cannot relax my questions ~~~ (I don't know how long I can stick to it, hahaha)
The difficulty of this question mainly lies in understanding the question and thinking transformation. Because of the stock background, the code is quite simple,... I still fell into the trap... Tears
SetBuying and selling are regarded as a roundTo maximize profits, you only need to meet the principles of low-price purchase and high-price sales.
For example, if prices = [3, 1, 4, 6, 5, 7]
Then, you can buy at 1, 4, 4, 6, 5, and 7.
In this way, total (4-1) + (6-4) + (7-5) = 7
The final code is as follows:
class Solution: # @param prices, a list of integer # @return an integer def maxProfit(self, prices): L=len(prices) rs=0 for i in range(0,L-1): if prices[i+1]>prices[i]: rs+=(prices[i+1]-prices[i]) return rs
Leetcode_num5_best time to buy and invalid stock II