`

Best Time to Buy and Sell Stock

阅读更多
Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

动态规划问题,实际上就是让我们在一个数组中找到两个元素的差最大,较小的元素在较大元素的左边。用一个变量profit来维护当前的最小元素,用max来维护当前最大的利润。代码如下:
public class Solution {
    public int maxProfit(int[] prices) {
        int profit = 0;
        int max = 0;
        for(int i = 1; i < prices.length; i++) {
            profit += prices[i] - prices[i - 1];
            if(profit < 0) profit = 0;
            if(profit > max) max = profit;
        }
        return max;
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics