题目描述
给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。
注意你不能在买入股票前卖出股票。
示例 1:
输入: [7,1,5,3,6,4]
输出: 5
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
总结
用low记录当前遇到的最小值(因为再往后遍历遇到最高值的更高值时,应该在最小值处买入)
Sample & Demo code
class Solution {
public int maxProfit(int[] prices) {
if (prices == null || prices.length <= 1) return 0;
int low = prices[0];
int rec = 0;
for (int i=1;i<prices.length;i++) {
if (prices[i]<low) {
low = prices[i];
}else if (prices[i]-low>=rec) {
rec = prices[i] - low;
}
}
return rec;
}
}
动态规划
class Solution {
public int maxProfit(int[] prices) {
int n = prices.length;
// base case: dp[-1][0] = 0, dp[-1][1] = -infinity
int dp_i_0 = 0, dp_i_1 = Integer.MIN_VALUE;
for (int i = 0; i < n; i++) {
// dp[i][0] = max(dp[i-1][0], dp[i-1][1] + prices[i])
dp_i_0 = Math.max(dp_i_0, prices[i] + dp_i_1); //prices[i] +(-买入的时候的价格);
// dp[i][1] = max(dp[i-1][1], -prices[i])
dp_i_1 = Math.max(dp_i_1, -prices[i]);
// System.out.println(dp_i_0+" : "+dp_i_1);
}
return dp_i_0;
}
}
分治算法
class Solution {
private int[] A;
public int maxProfit(int[] prices) {
if(prices.length < 2) return 0;
A = new int[prices.length-1];
for(int i = 0; i < A.length; i++) {
A[i] = prices[i+1] - prices[i];
}
return Math.max(0, find(0, A.length-1));
}
private int find(int low, int high) {
if(low == high) return A[low];
int mid = (low+high) / 2;
int le_sum = find(low, mid);
int ri_sum = find(mid+1, high);
int co_sum = helper(low, mid, high);
return Math.max(co_sum, Math.max(le_sum, ri_sum));
}
private int helper(int low, int mid, int high) {
int le = 0, ri = 0;
int left_sum = Integer.MIN_VALUE;
int right_sum = Integer.MIN_VALUE;
int sum = 0;
for(int i = mid; i >= low; i--) {
sum += A[i];
if(sum > left_sum) {
left_sum = sum;
le = i;
}
}
sum = 0;
for(int i = mid+1; i <= high; i++) {
sum += A[i];
if(sum > right_sum) {
right_sum = sum;
ri = i;
}
}
return left_sum + right_sum;
}
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock