# LeetCode Best Time to Buy and Sell Stock III

128人阅读 评论(0)

Description:

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.

Solution:

import java.util.*;

public class Solution {
public int maxProfit(int[] prices) {
int n = prices.length;
if (n == 0)
return 0;

int after[] = new int[n];
int before[] = new int[n];

int maxPrice = prices[n - 1], max = 0;
for (int i = n - 1; i >= 0; i--) {
maxPrice = Math.max(maxPrice, prices[i]);
max = Math.max(max, maxPrice - prices[i]);
after[i] = max;
}

int minPrice = prices[0];
max = 0;
for (int i = 0; i < n; i++) {
minPrice = Math.min(minPrice, prices[i]);
max = Math.max(max, prices[i] - minPrice);
before[i] = max;
}

max = 0;
for (int i = 0; i < n; i++)
max = Math.max(max, after[i] + before[i]);
return max;
}
}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：62753次
• 积分：3262
• 等级：
• 排名：第10459名
• 原创：288篇
• 转载：0篇
• 译文：0篇
• 评论：4条
文章分类
阅读排行
最新评论