Problem Statement
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).
Solution using python
Space Complexity 0(1)
1 2 3 4 5 6 7 8 9 10 11 12 13 | stocks=[7,1,5,2,4] def buy_sell_once(s): maxprofit=0 #first loop for i in range(len(s)-1): for j in range(i+1,len(s)): if s[j] - s[i] > maxprofit: maxprofit=s[j] - s[i] return maxprofit m=buy_sell_once(stocks) print(m) |
Space Complexity 0(1)
1 2 3 4 5 6 7 8 9 10 11 12 | stocks =[7,1,5,2,4] def buy_sell_once_ef(s): max_profit=0 min_price=stocks[0] for price in range(len(stocks)-1): min_price = min(min_price,price) profit =(price-min_price) max_profit=max(profit,max_profit) return max_profit m=buy_sell_once(stocks) print(m) |
Solution using Java
Link to GitHib : Code
Solution
- We need a variable to store the maxProfit
- We need to iterate through the array and Get the difference between selling price and buying price maxprofit+=prices[i+1]-prices[i]
- We need to make sure that selling price is greater than buying price. This check can be done using if condition if(prices[i+1] >prices[i])
public static int get(int [] prices) { int maxprofit=0; //loop through the array set . We need to keep on adding the profit //We need to buy and sell before buying others for(int i=0;i<prices.length-1;i++) { //We need to make sure that selling is greater than profit if(prices[i+1] >prices[i]) { maxprofit+=prices[i+1]-prices[i]; } } return maxprofit; }
No comments:
Post a Comment