best time to buy and sell stock

Best Time to Buy and Sell Stock

Question

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.

Example 1:

1
2
3
4
Input: [7, 1, 5, 3, 6, 4]
Output: 5
max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)

Example 2:

1
2
3
4
Input: [7, 6, 4, 3, 1]
Output: 0
In this case, no transaction is done, i.e. max profit = 0.

Analysis

Sharing my simple and clear C++ solution

循环过程中每次记录当前最小的min,并且在当前价格与min差值最大的时候更新max

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
public class {
public int maxProfit(int[] prices) {
int min=Integer.MAX_VALUE;
int max=0;
for(int i=0;i<prices.length;i++){
if(prices[i]<min)
min=prices[i];
if(prices[i]-min>max)
max=prices[i]-min;
}
return max;
}
}

Best Time to Buy and Sell Stock II

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).

Analysis

计算所有后者大于前者的元素对的差值并且求值即可

Code

1
2
3
4
5
6
7
8
9
10
public class {
public int maxProfit(int[] prices) {
int res=0;
for(int i=0;i<prices.length-1;i++){
if(prices[i+1]>prices[i])
res+=prices[i+1]-prices[i];
}
return res;
}
}

Best Time to Buy and Sell Stock III

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 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).

Analysis

A clean DP solution which generalizes to k transactions

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class {
public int maxProfit(int[] prices) {
int k=2;
int size=prices.length;
if(size<1) return 0;
int[][] f=new int[k+1][size];
int res=0;
for(int i=1;i<=k;i++){
int maxtmp=f[i-1][0]-prices[0];
for(int j=1;j<size;j++){
f[i][j]=Math.max(maxtmp+prices[j],f[i][j-1]);
maxtmp=Math.max(maxtmp,f[i-1][j]-prices[j]);
res=Math.max(f[i][j],res);
}
}
return res;
}
}