题目:

贪心算法
public int maxProfix(int[] prices) {
if (prices == null || prices.length == 0 || prices.length == 1) {
return 0;
}
int max = 0;
for (int i = 0; i < prices.length - 1; i++) {
if(prices[i+1] - prices[i] > 0){
max += prices[i + 1] - prices[i];
}
}
return max;
}
贪心算法原理
原理链接
动态规划
public class Soulution {
public int maxProfix(int[] prices) {
if (prices == null || prices.length == 0 || prices.length == 1) {
return 0;
}
int[][] dp = new int[prices.length][2];
dp[0][0] = 0;
dp[0][1] = -7;
for (int i = 1; i < prices.length; i++) {
dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i]);
dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] - prices[i]);
}
return dp[prices.length - 1][0];
}