Best Time to Buy and Sell Stock I
题意:每天只能买入或者卖出。在只进行一次交易的情况下,获得最大收益。
分析:动态规划。维护一个当前的最大收益和当前的最小价格。遍历数组。
复杂度:时间复杂度O(n),空间复杂度O(1)
代码:
public class Solution {
public int maxProfit(int[] prices) {
if (prices.length < 2) return 0;
int maxProfit = 0;
int curMin = prices[0];
for (int i = 1; i < prices.length; i++) {
curMin = Math.min(curMin, prices[i]);
maxProfit = Math.max(maxProfit, prices[i] - curMin);
}
return maxProfit;
}
}
Best Time to Buy and Sell Stock II
题意:不限制交易次数,但是每次手中只能有一只股票,求最大收益。
分析:贪心算法。先将数组转化为相邻数字之间的差值数组,,在求最大和。只要差值大于零,就算入收益。
复杂度:时间O(n),空间1
代码:
class Solution {
public int maxProfit(int[] prices) {
if(prices==null || prices.length==0 || prices.length==1) return 0;
int res = 0;
for(int i=0; i<prices.length-1; i++){
int diff = prices[i+1]-prices[i];
if(diff>0)
res += diff;
}
return res;
}
}
Best Time to Buy and Sell Stock III
题意:最多交易两次,求最大收益。
分析:首先将数组分为两个部分,两个部分分别用 Best Time to Buy and Sell Stock I 中的方法解,最后将两部分的额最大值求和。需要选择数组中的每一个值作为数组的划分点
复杂度:时间O(n^2),空间O(1)
class Solution {
public int maxProfit(int[] prices) {
//https://www.cnblogs.com/TenosDoIt/p/3436457.html
//首先将price分为两部分,两部分分别求解
//每一部分首先构造价格差价,然后求差价的最大子段和。详见链接
if(prices==null || prices.length==0 || prices.length==1)
return 0;
int res = 0;
for(int mid=1; mid<=prices.length-1; mid++){
int k1=0;
int k2=0;
int res1=0;
int res2=0;
for(int i=0; i<mid; i++){
if(k1<=0)
k1 = prices[i+1]-prices[i];
else
k1 += prices[i+1]-prices[i];
res1 = Math.max(res1, k1);
}
for(int j=mid; j<prices.length-1; j++){
if(k2<=0)
k2 = prices[j+1]-prices[j];
else
k2 += prices[j+1]-prices[j];
res2 = Math.max(res2, k2);
}
res = Math.max(res, res1+res2);
}
return res;
}
}
另外两道题参考 : https://blog.csdn.net/Dr_Unknown/article/details/51939121