Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Brute Force Solution
1
2
3
4
5
6
7
8
9
publicintmaxProfit(int[] prices) {
int maxp=0, low=Integer.MAX_VALUE;
for(int i=0;i<prices.length;i++){
if(prices[i]<low) low=prices[i];
if(prices[i]-low>maxp)
maxp=prices[i]-low;
}
return maxp;
}
DP Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
publicintmaxProfit(int[] prices) {
int maxp=0, tmp=0;
if (prices == null || prices.length <2) { return0;}
int[] t=newint[prices.length-1];
for(int i=0;i<prices.length-1;i++){
t[i]=prices[i+1]-prices[i];
}
for(int i=0;i<t.length;i++){
tmp+=t[i];
if(tmp>maxp) maxp=tmp;
if(tmp<0) tmp=0;
}
return maxp;
}
Best Time to Buy and Sell Stock II
Greedy Solution: trasaction once there exist profit.
1
2
3
4
5
6
7
8
9
publicintmaxProfit(int[] prices) {
if(prices.length == 0) return0;
int ans = 0;
for(int i=1; i<prices.length; i++){
if(prices[i] > prices[i-1])
ans += prices[i]-prices[i-1];
}
return ans;
}
DP Solution
1
2
3
4
5
6
7
8
9
10
11
12
publicintmaxProfit(int[] prices) {
int maxp=0, tmp=0,curmax=0;
if (prices == null || prices.length <2) { return0;}
int[] t=newint[prices.length-1];
for(int i=0;i<prices.length-1;i++){
t[i]=prices[i+1]-prices[i];
}
for(int i=0;i<t.length;i++){
if(t[i]>0) maxp+=t[i];
}
return maxp;
}
Best Time to Buy and Sell Stock III
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 at most two transactions. Note: You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
DP Solution
First thought: we can cut the array in half in n ways, and get the max profit from both sides using solution in the first question. This will be O(n^2), too LTE… Using DP to store the max profit from both sides? just scan twice from both directions and update the max profit array for [0…i] and [i…n-1]. Return the max value when a[i]+b[i] is max.