Leetcode-best-time-to-buy-and-sell-stock

来源:互联网 发布:深圳淘宝培训班免费 编辑:程序博客网 时间:2024/06/06 04:15

题目描述


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.

只允许做一次交易,则找出最高股价-最低股价。

动态规划问题:dp[i]表示第i天的收益,则等于prices[i]-min(prices[0...i-1]),即第i天的股价减去前i-1天的最低股价,如果第i天的股价比前i-1天的最低股价还要低,则更新最小值,供后续计算使用,思路很清晰了,下面就是代码。

public class Solution {    public int maxProfit(int[] prices) {         int n = prices.length;         if(n == 0)         return 0;         int maxpro = 0;         int min = prices[0];         for(int i=1; i<n; i++){         min = Math.min(prices[i], min);  //比较第i天的股价和前i-1天的最低价,取最小值         if(prices[i] - min > maxpro)         maxpro = prices[i] - min;  //maxpro表示第i天的收益,就是第i天的股价减去前i-1天的最低价         }         return maxpro;    }}


0 0