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 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
- Go through the price array;
- If I don't have any stock in hands and today's price (i) is lower than tomorrow (i+1), I will buy in the stock
- If do have stock and today's price (i) is higher than tomorrow (i+1), I will sale my stock and make profit.
- Just sum up the profit.
Challenge
The main challenge of this question is to consider all the possible user cases.- The length of price can be less than 2.
- If there is no price, we can not buy stock.
- If there is only one price, we can buy stock but not sell it.
- The price can be 0;
- My first solution thinks that the price of buying in stock is equal to zero when there is no stock in hands. However, it ignores the scenario that we can buy the stock in zero price.
- To avoid the out-of-index exception, the for-loop will be end at the price before the last one (prices.length - 1). If I still have stock in hand after the for-loop and I have profit, I will sale my stock.
Code (Java)
public class Solution {public int maxProfit(int[] prices) {
int m = 0; // save the profit
int buyINPrice =-1; // save the price and indicates if I have stock in hand or not
int i;
if (prices.length >= 2) {
for (i=0;i<prices.length-1;i++) {
if (buyINPrice == -1 ) {
// when I have no stock
if (prices[i] < prices[i+1]) {
buyINPrice = prices[i];
}
} else {
// when I have stock
if (prices[i] > prices [i+1]) {
m = m + (prices[i] - buyINPrice);
buyINPrice = -1;
}
}
}
if (buyINPrice >= 0) {
if (prices[i] > buyINPrice) {
m = m + (prices[i] - buyINPrice);
buyINPrice = 0;
}
}
return m;
} else {
return 0;
}
}
}