动态规划题目:Say you have an array for which the i-th element is the price of a given stock on day i.Design an algorithm and implement it to nd the maximum pro t. 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).
代码:
import java.io.ObjectInputStream.GetField;
public class Max_Rock_Profit {
static int Rock_Price[] = { 2, 5, 8, 15, 4, 28, 20, 33 };
static int N = Rock_Price.length;
public static int Max_Profit(int a[]) {
int max = Integer.MIN_VALUE;
int Left_min = Integer.MAX_VALUE;
int[] Left_Max = new int[N];
int[] Right_Max = new int[N];
int diff;
for (int i = 0; i < N; i++) {
if (a[i] < Left_min)
Left_min = a[i];
diff = a[i] - Left_min;
if (diff > max)
max = diff;
Left_Max[i] = max;
}
max = Integer.MIN_VALUE;
int Max_Right = Integer.MIN_VALUE;
for (int j = N - 1; j >= 0; j--) {
if (a[j] > Max_Right)
Max_Right = a[j];
diff = Max_Right - a[j];
if (diff > max)
max = diff;
Right_Max[j] = max;
}
max = Integer.MIN_VALUE;
for (int k = 0; k < N - 1; k++) {
int m = Left_Max[k] + Right_Max[k + 1];
if (m > max)
max = m;
}
return max;
}
public static void main(String[] args) {
System.out.println(Max_Profit(Rock_Price));
}
}