121. 买卖股票的最佳时机

image.png

暴力解法(超时)

  1. class Solution {
  2. public int maxProfit(int[] prices) {
  3. int maxProfit = 0;
  4. for(int i = 0 ; i < prices.length; i++ ) {
  5. for(int j = i + 1; j < prices.length; j ++) {
  6. maxProfit = Math.max(maxProfit,prices[j] - prices[i]);
  7. }
  8. }
  9. return maxProfit;
  10. }
  11. }

贪心

  1. class Solution {
  2. public int maxProfit(int[] prices) {
  3. //贪心
  4. //取左侧的最小值
  5. int low = Integer.MAX_VALUE;
  6. int res = 0;
  7. for(int i = 0 ; i < prices.length; i++ ) {
  8. low = Math.min(low,prices[i]);
  9. res = Math.max(res, prices[i] - low);
  10. }
  11. return res;
  12. }
  13. }

动态规划

  1. class Solution {
  2. public int maxProfit(int[] prices) {
  3. int size = prices.length;
  4. //dp[i][0] 代表第i天持有股票的最大收益
  5. //dp[i][1] 代表第i天不持有股票的最大收益
  6. int [][] dp = new int[size][2];
  7. dp[0][0] = -prices[0];
  8. dp[0][1] = 0;
  9. for(int i = 1 ; i < size ; i++ ) {
  10. dp[i][0] = Math.max(dp[i - 1][0], - prices[i]);
  11. dp[i][1] = Math.max(dp[i - 1][1],dp[i - 1][0] + prices[i]);
  12. }
  13. return dp[size - 1][1];
  14. }
  15. }

动态规划(滚动数组)

  1. class Solution {
  2. public int maxProfit(int[] prices) {
  3. // 求a除以2的n次方的余数 等价于 a & (2的n次方 - 1)
  4. int size = prices.length;
  5. int [][] dp = new int[2][2];
  6. //持有股票
  7. dp[0][0] = -prices[0];
  8. //不持有股票
  9. dp[0][1] = 0;
  10. for(int i = 1 ; i < size ; i++) {
  11. //dp[i % 2][0] = Math.max(dp[ (i - 1) % 2][0], -prices[i]);
  12. dp[i & 1][0] = Math.max(dp[ (i - 1) & 1][0], -prices[i]);
  13. //dp [i % 2][1] = Math.max( dp[ (i - 1) % 2][1],dp[ (i - 1) % 2 ][0] + prices[i]);
  14. dp [i & 1][1] = Math.max( dp[ (i - 1) & 1][1],dp[ (i - 1) & 1 ][0] + prices[i]);
  15. }
  16. return dp[ (size - 1) & 1][1];
  17. }
  18. }