暴力解法(超时)
class Solution { public int maxProfit(int[] prices) { int maxProfit = 0; for(int i = 0 ; i < prices.length; i++ ) { for(int j = i + 1; j < prices.length; j ++) { maxProfit = Math.max(maxProfit,prices[j] - prices[i]); } } return maxProfit; }}
贪心
class Solution { public int maxProfit(int[] prices) { //贪心 //取左侧的最小值 int low = Integer.MAX_VALUE; int res = 0; for(int i = 0 ; i < prices.length; i++ ) { low = Math.min(low,prices[i]); res = Math.max(res, prices[i] - low); } return res; }}
动态规划
class Solution { public int maxProfit(int[] prices) { int size = prices.length; //dp[i][0] 代表第i天持有股票的最大收益 //dp[i][1] 代表第i天不持有股票的最大收益 int [][] dp = new int[size][2]; dp[0][0] = -prices[0]; dp[0][1] = 0; for(int i = 1 ; i < size ; i++ ) { dp[i][0] = Math.max(dp[i - 1][0], - prices[i]); dp[i][1] = Math.max(dp[i - 1][1],dp[i - 1][0] + prices[i]); } return dp[size - 1][1]; }}
动态规划(滚动数组)
class Solution { public int maxProfit(int[] prices) { // 求a除以2的n次方的余数 等价于 a & (2的n次方 - 1) int size = prices.length; int [][] dp = new int[2][2]; //持有股票 dp[0][0] = -prices[0]; //不持有股票 dp[0][1] = 0; for(int i = 1 ; i < size ; i++) { //dp[i % 2][0] = Math.max(dp[ (i - 1) % 2][0], -prices[i]); dp[i & 1][0] = Math.max(dp[ (i - 1) & 1][0], -prices[i]); //dp [i % 2][1] = Math.max( dp[ (i - 1) % 2][1],dp[ (i - 1) % 2 ][0] + prices[i]); dp [i & 1][1] = Math.max( dp[ (i - 1) & 1][1],dp[ (i - 1) & 1 ][0] + prices[i]); } return dp[ (size - 1) & 1][1]; }}