zoukankan      html  css  js  c++  java
  • Leetcode: 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.

    这道题求进行一次交易能得到的最大利润。如果用brute force的解法就是对每组交易都看一下利润,取其中最大的,总用有n*(n-1)/2个可能交易,所以复杂度是O(n^2)。
    Maximum Subarray非常类似,用“局部最优和全局最优解法”。思路是维护两个变量,一个是到目前为止最好的交易,另一个是在今天卖出的最佳交易(也就是局部最优。

    *maxCur = maximum value sold today

    *maxSoFar = maximum value found so far

    class Solution {
        public int maxProfit(int[] prices) {
            // local[i] = max(local[i-1] + prices[i] - prices[i-1], prices[i] - prices[i-1])
            // global[i] = max(global[i-1], local[i] > 0? local[i] : 0)
            int local = 0, global = 0;
            for (int i = 1; i < prices.length; i++) {
                int diff = prices[i] - prices[i-1];
                local = Math.max(local + diff, diff);
                global = Math.max(global, local > 0? local : 0);
            }
            return global;
        }
    }
  • 相关阅读:
    11
    961. N-Repeated Element in Size 2N Array
    用numpy.pad()对图像进行填充及简单的图像处理
    709. To Lower Case
    929. Unique Email Addresses
    771. Jewels and Stones
    谭凯---访谈录
    如何拍照
    主题阅读法
    社会各职业工作重心和流程
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/3758233.html
Copyright © 2011-2022 走看看