动态规划:
1.class Solution {
public int maxProfit(int[] prices) {
int[] profit = new int[prices.length];
if(prices.length==0)
return 0;
for (int i = 0; i < prices.length; i++)
for (int j = 0; j < i; j++)
profit[i] = Math.max(profit[j] + prices[i] - prices[j], profit[i - 1]);
return profit[prices.length-1];
}
}
2.class Solution {
public int maxProfit(int[] prices) {
int[] profit = new int[prices.length];
if(prices.length==0)
return 0;
for (int i = 1; i < prices.length; i++)
profit[i] = Math.max(profit[i - 1] + prices[i] - prices[i - 1], profit[i - 1]);
return profit[prices.length-1];
}
}
这题有点怪,我的理解好像有点出错
public class MaxProfit122 {
public static void main(String[] args) {
int[] prices = { 7, 1, 5, 3, 6, 7 };
if (prices.length < 2)
System.out.println(0);
int sum = 0;
for (int i = 0; i < prices.length - 1; i++)
if (prices[i + 1] - prices[i] > 0)
sum += prices[i + 1] - prices[i];
System.out.println(sum);
}
}