题目:一个人一天只能进行最多两次买和两次卖,并且只有卖了才能继续买。问一天可以获得的最大收益,要采用时间复杂度低的实现。
输入:5 2,4,6,8,10.输出:8 (2买,10卖)
输入:6 10,22,5,75,65,80.输出:87 (10买,22卖,5买,80卖)
动态规划解决方法:设置数组dp[i][j]表示:prices[i]买入到prices[j]卖出的收益。则得出dp[i][j]为
0 12 -5 65 55 70
0 0 -17 53 43 58
0 0 0 70 60 75
0 0 0 0 -10 5
0 0 0 0 0 15
0 0 0 0 0 0
然后:先找出最大值的位置和买入卖出的时间,题中是75最大,买入i=2,卖出j=5
然后根据买入卖出的时间,算出除此之外时间段的最大值
代码如下:
- public static int maxProfit(int[] prices, int length) {
- int res = 0;
- int dp[][] = new int[length][length];
- for (int i = 0; i < length - 1; i++) {
- for (int j = i + 1; j < length; j++) {
- dp[i][j] = prices[j] - prices[i];
- System.out.print(dp[i][j] + " ");
- }
-
- }
-
- int max = 0;
- int ma2 = 0;
- int start = 0;
- int end = 0;
- for (int i = 0; i < length; i++)
- for (int j = i + 1; j < length; j++) {
- if (dp[i][j] > max) {
- max = dp[i][j];
- start = i;
- end = j;
- }
- }
- System.out.println(start + " " + end + " " + max);
- for (int i = 0; i < start; i++)
- for (int j = i + 1; j < start; j++) {
- if (dp[i][j] > ma2) {
- ma2 = dp[i][j];
-
- }
- }
-
- if (end < length - 1)
- for (int i = end + 1; i < length; i++) {
- for (int j = i + 1; j < length; j++) {
- if (dp[i][j] > ma2) {
- ma2 = dp[i][j];
-
- }
- }
- }
- res = max + ma2;
- return res;
- }