Best Time to Buy and Sell Stock 系列

Best Time to Buy and Sell Stock I

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

解决思路

只可以买卖一次,则遍历过程中记录前面的最低价格,然后维护最大收益差即可。

程序

public class Solution {
    public int maxProfit(int[] prices) {
        if (prices == null || prices.length < 2) {
            return 0;
        }

        int max = 0;
        int min = prices[0];

        for (int i = 1; i < prices.length; i++) {
            min = Math.min(min, prices[i]);
            max = Math.max(max, prices[i] - min);
        }

        return max;
    }
}

Best Time to Buy and Sell Stock II

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 as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

解决思路

比较相邻的元素,如果当前元素比前面的元素更大,则进行累计。最后输出即可。

程序

public class Solution {
    public int maxProfit(int[] prices) {
        if (prices == null || prices.length == 0) {
            return 0;
        }
        int sum = 0;
        for (int i = 1; i < prices.length; i++) {
            if (prices[i] > prices[i - 1]) {
                sum += prices[i] - prices[i - 1];
            }
        }
        return sum;
    }
}

Best Time to Buy and Sell Stock III

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.

Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

解决思路

技巧:前后分别扫一遍,从前往后扫记录下以当前节点卖出的最大收益(方法如问题I),从后往前记录以当前节点卖出之后,后面再交易一次能够得到的最大收益。

最后同时扫描这两个数组,然后记录下两个数组的之和的最大值。

时间复杂度为O(n).

程序

public class Solution {
    public int maxProfit(int[] prices) {
		if (prices == null || prices.length < 2) {
			return 0;
		}
		int len = prices.length;
		int[] forward = new int[len];
		int[] backward = new int[len];

		// cal backward
		int min = prices[0];
		for (int i = 1; i < len; i++) {
			min = Math.min(min, prices[i]);
			backward[i] = prices[i] - min;
		}

		// cal forward
		int max = prices[len - 1];
		for (int i = len - 2; i >= 0; i--) {
			max = Math.max(max, prices[i + 1]);
			forward[i] = Math.max(max - prices[i + 1], forward[i + 1]);
		}

		int maxProfit = 0;
		for (int i = 0; i < len; i++) {
			maxProfit = Math.max(maxProfit, backward[i] + forward[i]);
		}

		return maxProfit;
	}
}

Best Time to Buy and Sell Stock IV

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 k transactions.

Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

解决思路

1.  dfs方法 + dp优化

二维数组dp[i, j]代表在区间[i, j]中能够获得的最大收益。

程序

public class Solution {
    private int max = 0;

	public int maxProfit(int k, int[] prices) {
		if (prices == null || prices.length < 2 || k <= 0) {
			return 0;
		}
		if (k > prices.length / 2) {
			k = prices.length / 2;
		}
		int len = prices.length;
		int[][] maxOneSellDp = getDpOptimize(prices);
		helper(prices, 0, len, k, 0, maxOneSellDp);
		return max;
	}

	private int[][] getDpOptimize(int[] prices) {
		int n = prices.length;
		int[][] dp = new int[n][n];

		for (int i = 0; i < n - 1; i++) {
			int min = prices[i];
			for (int j = i + 1; j < n; j++) {
				min = Math.min(min, prices[j]);
				dp[i][j] = prices[j] - min;
			}
		}
		return dp;
	}

	private void helper(int[] prices, int start, int end, int k, int profit,
			int[][] maxOneSellDp) {
		if (start > end || k < 0) {
			return;
		}
		if (profit > max) {
			max = profit;
		}
		for (int i = start + 1; i < end; i++) {
			// int maxOneSell = getMaxOneSell(prices, start, i); // dp optimize
			int maxOneSell = maxOneSellDp[start][i];
			helper(prices, i + 1, end, k - 1, profit + maxOneSell, maxOneSellDp);
		}
	}
}

第一种方法TLE。

时间: 2024-11-10 14:06:38

Best Time to Buy and Sell Stock 系列的相关文章

Best Time to Buy and Sell Stock系列

1.Best Time to Buy and Sell Stock II 1 class Solution { 2 public: 3 int maxProfit(vector<int>& prices) { 4 if(prices.size() < 1) //prices.size is unsigned int 5 return 0; 6 int pro = 0; 7 for(int i=0; i<prices.size()-1; i++) 8 { 9 if(price

Java for LeetCode 188 Best Time to Buy and Sell Stock IV【HARD】

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 k transactions. 解题思路: 本题是Best Time to Buy and Sell Stock系列最难的一道,需要用到dp,JAVA实现如下: public i

[Lintcode] Best Time to Buy and Sell Stock I, II, III &amp;&amp; Maximum Subarray

买卖股票系列 && Subarray 相关题目: Best Time to Buy and Sell Stock I && II && III (IV 单独开贴) Maximum Subarray I && II 为什么这些我要总结到一起呢?因为思路基本一致. 题目简略: 买卖股票1: 一次买卖,利润最大. 买卖股票2: N次买卖,利润最大. 买卖股票3: 2次不重叠的买卖,利润最大. Maximum Subarray: Given an a

[leetcode]_Best Time to Buy and Sell Stock I &amp;&amp; II

一个系列三道题,我都不会做,google之答案.过了两道,第三道看不懂,放置,稍后继续. 一.Best Time to Buy and Sell Stock I 题目:一个数组表示一支股票的价格变换.要求只买卖一次,获得最大收益. 思路:一开始我认为是寻找最大.最小值,但由于最大值不一定总是出现在最小值的后面,因此WA. 参考思路:DP.对第i个价格,减去前i-1个价格中的最小值(保证该收益是在第i个价格卖出的最大收益),其收益与之前获得的最大收益相比. 代码: 1 public int max

[LeetCode] Best Time to Buy and Sell Stock III 买股票的最佳时间之三

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. Note:You may not engage in multiple transactions at the same time (ie,

LeetCode Best Time to Buy and Sell Stock II

Best Time to Buy and Sell Stock II Total Accepted: 41127 Total Submissions: 108434 My Submissions Question Solution 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

Best Time to Buy and Sell Stock

Best Time to Buy and Sell Stock I Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorith

[Leetcode][JAVA] Best Time to Buy and Sell Stock I, II, III

Best Time to Buy and Sell Stock Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm

[LeetCode]Best Time to Buy and Sell Stock III 动态规划

本题是Best Time to Buy and Sell Stock/的改进版. 本题中,可以买最多买进卖出两次股票. 买两次股票可以看成是第0~i天买进卖出以及第i+1~n-1天买进卖出两部分.这要枚举i并求出0th~ith的最大利益与(i+1)th~(n-1)th的最大利益之和的最大值就是买进卖出两次可以得到的最大利益.即状态转移方程: dp[0,n-1]=max{dp[0,k]+dp[k+1,n-1]},k=1,...,n-2 而只买进卖出一次的最大利润通过0th~ith可以求得. 这里求