[leetcode]121. Best Time to Buy and Sell Stock

来源:互联网 发布:网络神豪系统txt下载 编辑:程序博客网 时间:2024/06/06 08:34

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.

动态规划,遍历数组,记录出现过的最小价格,作为买入价格。并计算当天出售的利益,如果利益大于最大利益,最大利益为当天利益。

public class Solution {    public int maxProfit(int[] prices) {        if(prices.length==0){            return 0;        }        int maxProfit=0;        int minPrice=prices[0];        for(int i=1;i<prices.length;i++){            minPrice=Math.min(minPrice,prices[i]);            maxProfit=Math.max(prices[i]-minPrice,maxProfit);        }        return maxProfit;    }}


1 0
原创粉丝点击