BestTimeToBuyAndSell

来源:互联网 发布:2017淘宝一天的交易额 编辑:程序博客网 时间:2024/06/05 20:26

问题描述:股票在每天的不同时刻有不同的价格。用int数组来保存股票在一天中不同时刻的价格。要求出当天买卖股票的最大利润。如果价格一直递减,利润为0


解决:做过了最大子串那题,能够很明显的感觉到这是一道动态规划问题。如果local表示局部最优,下一个local = max(local + prices[i]-prices[i-1],0)。再每次更新全局最优即可。

/* * 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. Example 1:Input: [7, 1, 5, 3, 6, 4]Output: 5 max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)Example 2:Input: [7, 6, 4, 3, 1]Output: 0 In this case, no transaction is done, i.e. max profit = 0. */public class BestTimeToBuyAndSell {    public int maxProfit(int[] prices) {         if(prices == null || prices.length == 0)                 return -1;                  int local = 0;         int global = 0;         for(int i=1; i<prices.length; i++) {                 local = Math.max(local + prices[i]-prices[i-1], 0);                 global = Math.max(global, local);         }         return global;    }}



原创粉丝点击