Best Time to buy and sell

public class Solution {
    /**
     * @param prices: Given an integer array
     * @return: Maximum profit
     */
    public int maxProfit(int[] prices) {
    	if (prices.length == 0) {
    	return 0;
    }
    int[] dp = new int[prices.length];
    int ans = 0;
    for (int i = 1; i < prices.length; i++) {
    	dp[i] = Math.max(dp[i - 1] + prices[i] - prices[i - 1], prices[i] - prices[i - 1]);
    	ans = Math.max(ans, dp[i]);
    }
    return ans;
    }
}

最后更新于

这有帮助吗?