Algorithm-buying and selling stock problem
I haven't posted a blog in August, let's practice dynamic planning.
The source of this topic is the NetEase written test
题目描述:现在有n个人排队买票,已知是早上八点开始卖票,这n个人买票有两种方式
第一种是每个人都可以单独去买自己的票,第i个人花费i秒。
第二种是每个人都可以选择和后面的人一起买票,第i个人和第i+1个人一共花费b[i]秒。
最后一个人只能和前一个一起买票或者自己单独购买,求花费的最短时间。
It can be seen that the problem of buying tickets is a typical dynamic programming problem. Why do you say that? Because the current minimum time depends on the previous ticket purchase decision.
After determining that it is a dynamic programming problem, our main task is to find the state transition equation.
The following example illustrates
int[] a={
3,5,7,6};
int[] b={
6,11,13};
When solving this problem, we are actually looking for the minimum value we accumulated in the array a from position 0 to position ptr
For example, when ptr=0, the current shortest time is obviously
dp[ptr]=a[0]
When ptr=1, the current shortest time is
dp[ptr]=min(a[0]+a[1],b[0])
Obviously, when ptr=2, the shortest time is min(dp[ptr-1]+a[ptr],dp[ptr-2]+b[ptr-1]).
dp[ptr]=min(dp[ptr-1]+a[ptr],dp[ptr-2]+b[ptr-1])
The rest can continue recursive
So we came to this conclusion
/**
* @param a 单独购买的时间
* @param b 两个人一起买的时间
* @return
*/
public static int timeToClose(int[] a,int[] b){
if (a.length==0||a.length==1){
return a.length==0?0:a[0];
}
int[] dp=new int[a.length];
dp[0]=a[0];
dp[1]=Math.min(b[0],a[0]+a[1]);
int ptr=2;
while (ptr<a.length){
//a[ptr]表示单独购买的花费时间,dp[ptr-1]表示从第0个人到第ptr-1个人总共花费的最小时间
//b[ptr-1]表示第ptr个人和第ptr-1个人一起花费的时间,dp[ptr-2]表示从第0个人到第ptr-2个人总共花费的最小时间
dp[ptr++]=Math.min(a[ptr]+dp[ptr-1],b[ptr-1]+dp[ptr-2]);
}
return dp[dp.length-1];
}