LeetCode 121. Best Time to Buy and Sell Stock

原题链接在这里:https://leetcode.com/problems/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.

题解:

Let local denotes up to i, maximum profit when last transaction must happend at i. If it is smaller than 0, reset as 0.

local = Math.max(local + diff, 0). 

Maintain the global maximum.

global = Math.max(local, global).

Time Complexity: O(n). Space: O(1).

AC Java:

 1 public class Solution {
 2     public int maxProfit(int[] prices) {
 3         //采用局部最优和全局最优
 4         if(prices == null || prices.length <= 1){
 5             return 0;
 6         }
 7         int local = 0;
 8         int global = 0;
 9         for(int i = 1; i<prices.length; i++){
10             local = Math.max(local+prices[i]-prices[i-1],0);
11             global = Math.max(local,global);
12         }
13         return global;
14     }
15 }

类似Maximum SubarrayMaximum Difference Between Increasing Elements.

跟上Best Time to Buy and Sell Stock IIBest Time to Buy and Sell Stock IIIBest Time to Buy and Sell Stock IVBest Time to Buy and Sell Stock with CooldownBest Time to Buy and Sell Stock with Transaction Fee.

posted @ 2015-09-15 23:05  Dylan_Java_NYC  阅读(356)  评论(0编辑  收藏  举报