买卖股票的最佳时机
题目来源:LeetCode 121.买卖股票的最佳时机
思路
这里题目要求最多只允许完成一笔交易。属于一道简单题,暴力法很容易想到,但是其实遍历一遍就可以了,设置一个最小值,遍历的时候不断更新最小值,用当前价格减去最小值即可得到当前天卖出股票的收益,取最大的收益即可。
class Solution {
public int maxProfit(int[] prices) {
int minPrice = Integer.MAX_VALUE;
int res = 0;
for (int i = 0; i < prices.length; i++) {
minPrice = Math.min(minPrice, prices[i]);
res = Math.max(res, prices[i]-minPrice);
}
return res;
}
}
买卖股票的最佳时机2
题目来源:LeetCode 122.买卖股票的最佳时机 II
思路
这道题是一个变形,买卖股票的次数从题目一的一次变为了无数次。这还是一道简单题。思路也比较简单,只需要找出所有非严格递增段,最大值减去最小值即为这一段的最大收益,每段的收益相加即可。
class Solution {
public int maxProfit(int[] prices) {
int minIndex = 0;
int res = 0;
for (int i = 1; i < prices.length; i++) {
if (prices[i] < prices[i-1]) {
res += prices[i-1]-prices[minIndex];
minIndex = i;
}
}
if (minIndex != prices.length-1) {
res += prices[prices.length-1]-prices[minIndex];
}
return res;
}
}
买卖股票的最佳时机3
题目来源:LeetCode 123.买卖股票的最佳时机 III
思路
之前做东方财富的笔试遇到过这道题。
这道题也是一个变形,买卖股票的次数变成了最多可以完成两笔交易。这道题就变成了一道困难题。
class Solution {
public int maxProfit(int[] prices) {
int buy1 = Integer.MAX_VALUE;
int buy2 = Integer.MAX_VALUE;
int pro1 = 0;
int pro2 = 0;
for (int i = 0; i < prices.length; i++) {
buy1 = Math.min(buy1, prices[i]);
pro1 = Math.max(pro1, prices[i]-buy1);
buy2 = Math.min(buy2, prices[i]-pro1);
pro2 = Math.max(pro2, prices[i]-buy2);
}
return pro2;
}
}