【DP&数组】Best Time to Buy and Sell Stock

来源:互联网 发布:绿色上网软件手机软件 编辑:程序博客网 时间:2024/05/18 00:35

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.

题意:股票最多买一次、卖一次

解法:遍历数组,固定住当前最小值,以后的元素若是大于它则重设利润值max,否则重设最小值index

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

解法二:将数组中prices[i+1]-prices[i]建立一个新数组,可以将问题转化成求数组的最大连续子数组和

子段和= prices[j]-prices[j-1]+prices[j-1]-prices[j-2]+...+prices[i]-prices[i-1] = prices[j]-prices[i-1], 即prices[j]是最大价格,prices[i-1]是最小价格,且他们满足前后顺序关系

public class Solution {    public int maxProfit(int[] prices) {                if(prices == null || prices.length==0 || prices.length==1) return 0;        int sum = 0, curSum = 0;        for(int i=1; i<prices.length; i++){            if(curSum > 0)            curSum += prices[i] - prices[i-1];            else curSum = prices[i] - prices[i-1];                        sum = Math.max(curSum ,sum);        }        return sum;    }}


0 0