动态规划

动态规划题目: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));
}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值