Python
- key differences between List and Arrays
- Python collections ChainMap
- Array : Find median in an integer array
- Array : Find middle element in an integer array
- Array : Find out the duplicate in an array
- Array : Find print all subsets in an integer array
- Program : Array : Finding missing number between from 1 to n
- Array : Gap and Island problem
- Python collections
- Python Program stock max profit
- Reverse words in Python
- Python array duplicate program
- Coin change problem in python
- Python Write fibonacci series program
- Array : find all the pairs whose sum is equal to a given number
- Find smallest and largest number in array
- Iterate collections
- List comprehensions in Python
- key differences between List and Arrays
- Program: Calculate Pi in Python
- String Formatting in Python
- Python counters
- python tuples
- Python deque
- Python dictionary
- Python Lists
- python namedtuple
Buy and sell Stock to get Max profit
Whether you're a seasoned trader or a beginner, understanding the art of stock trading can lead to substantial financial gains. This is important that will gain profit in stock trading. The program we will solve here from an integer array of stock price at what point we sell our share to gain maximum profit.
In this exercise we have given the array of integer values. form this array we have to find at what point we need to exit form the stock to gain the maximum profit.
def max_profit(prices):
if len(prices) < 2:
return 0
min_price = prices[0]
max_profit = 0
for i in range(1, len(prices)):
if prices[i] < min_price:
min_price = prices[i]
else:
profit = prices[i] - min_price
if profit > max_profit:
max_profit = profit
return max_profit
prices = [7, 1, 5, 3, 6, 4]
profit = max_profit(prices)
print(profit)
# Output: 5
In this example, the prices
list is [7, 1, 5, 3, 6, 4]
, and the max_profit
function is called to calculate the maximum profit from buying and selling stocks based on these prices.