
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Best Time to Buy and Sell Stock II in Python
Suppose we have an array A, here A[i] is indicating the price of a given stock on day i. We have to find the maximum profit. We can complete as many transactions as we like. (Transaction means to buy and sell stocks). But we have to keep in mind that we may not engage in multiple transactions at the same time. So we have to sell the stock before buying the new one.
Suppose the array is like A = [7, 1, 5, 3, 6, 4], then the result will be 7. As we can see, if we buy on day 2 (index 1), then it will take 1 as a buying price. Then if we sell on day 3, the profit will be 5 – 1 = 4. Then buy on day 4, and sell on day 5, so profit will be 6 – 3 = 3
To solve this, follow these steps −
- let answer = 0
- for i in range 0 to n – 1 (n is the number of elements in A) −
- if A[i] – A[i – 1] > 0, then
- answer := answer + A[i] – A[i – 1]
- if A[i] – A[i – 1] > 0, then
- return answer
Example
Let us see the implementation to get a better understanding
class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ ans = 0 for i in range(1,len(prices)): if prices[i] - prices[i-1] >0: ans+=(prices[i] - prices[i-1]) return ans ob1 = Solution() print(ob1.maxProfit([7,2,5,8,6,3,1,4,5,4,7]))
Input
print(ob1.maxProfit([7,2,5,8,6,3,1,4,5,4,7]))
Output
13
- Related Articles
- Best Time to Buy and Sell Stock in Python
- Best Time to Buy and Sell Stock III in Python
- Best Time to Buy and Sell Stock IV in C++
- Best Time to Buy and Sell Stock with Cooldown in C++
- Program to find maximum profit we can make after k Buy and Sell in python
- What is the best way to get stock data using Python?
- What is the best site to invest money in stock market?
- Best Prenatal Vitamins You Can Buy Over the Counter
- Find the minimum and maximum amount to buy all N candies in Python
- Best Buy Recalls Insignia Air Fryers and Air Fryer Ovens After Reports of Fires
- Best way to store date/time in MongoDB?
- Which is the best site to buy back-covers, flip-covers, and screen guards for mobile phones?
- Write the difference between stock market and stock exchange.
- When to sell Crypto?
- I buy a T.V. for $Rs.\ 10,000$ and sell it at a profit of $20 \%$. How much money do I get for it?

Advertisements