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:
To make a profit, we have to buy in a low price and sell in a higher price. We can make profits when the prices are going up.
So we can take one transaction if the stock would go up the second day.
Why not hold and wait?
1. prices[] = {1,2,3,4,5}. 5 - 1 = (2-1) + (3-2) + (4-3) + (5-4).
2. prices[] = {1,3,2,5}. 5 - 1 < (3-1) + (5-2).
i.e. we will not lose money when prices going down, and make money as soon as prices going up.
public class Solution {
public int maxProfit(int[] prices) {
int profit = 0;
for(int i = 0; i < prices.length-1; i++){
if(prices[i+1] > prices[i])
profit = profit + (prices[i+1] - prices[i]);
}
return profit;
}
}
No comments:
Post a Comment