贪心算法典型例题。
题目
做过股票交易的都知道,想获取最大利润,就得从最低点买入,最高点卖出。这题刚好可以用暴力,一个数组中找到最大的数跟最小的数,然后注意一下最小的数在最大的数前面即可。从一个数组中选两个数作比较,可以选用两个for循环。这题用dp同理,不过dp数组存状态是多余的。
时间复杂度: O(n^2),空间复杂度: O(1)。
public class Solution {
public int maxProfit(int[] prices) {
int max = 0;
for (int i = 0; i < prices.length - 1; i++) {
for (int j = i + 1; j < prices.length; j++) {
int profit = prices[j] - prices[i];
if (profit > max) {
max = profit;
}
}
}
return max;
}
}
不过超时了,可以优化一下,从前往后遍历,每遍历到一个数,即每去到一天时,去存最低价跟最大利润,因为最低价购入可以得到更大利润,最高价直接更新最大利润。
时间复杂度: O(n),空间复杂度: O(1)。
public class Solution {
public int maxProfit(int[] prices) {
int pre = prices[0];
int ans = 0;
for (int i = 0; i < prices.length; i++) {
ans = Math.max(ans, prices[i] - pre);
pre = Math.min(pre, prices[i]);
}
return ans;
}
}
贪心的策略是,每到一个数可存到一个局部最优解,而遍历完后做一次次更新去得到目标值。