zoukankan      html  css  js  c++  java
  • 122. Best Time to Buy and Sell Stock II

    题目:

    Say you have an array for which the ith element is the price of a given stock on day i.

    Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). 

    Hide Tags
     Array Greedy 

    链接: http://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/

    题解:

    买卖股票,可以多次transactions。使用Greedy贪婪法。假如每天的股票价值比前一天高,则差值可以计算入总结果中。原理是类似1,2,3,4,5,除第一天外每天先卖后买的收益其实等于局部最小值1和局部最大值5之间的收益。

    Time Complexity - O(n), Space Complexity - O(1)。

    public class Solution {
        public int maxProfit(int[] prices) {   //greedy
            if(prices == null || prices.length == 0)
                return 0;
            int result = 0;
                
            for(int i = 0; i < prices.length; i++){
                if(i > 0 && prices[i] - prices[i - 1] > 0)
                    result += prices[i] - prices[i - 1];
            }
            
            return result;
        }
    }

    Update:

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

     

    那么问题来了,为什么用Greedy这样算的结果会是最优? 因为只有上升序列会提供profit,而在一个上升序列里比如1,2,3,4,5,最后的profit等于 p[last] - p[first], 同时也等于所有p[i] - p[i-1]的和。discussion发现有篇写得很好,收在reference里了。

    二刷:

    和一刷方法一样。使用逐步累积的profit来求得最后总的最大profit。

    Java:

    Time Complexity - O(n), Space Complexity - O(1)。

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

    Reference:

    https://leetcode.com/discuss/6198/why-buying-day-and-selling-day-day-day-gauruntees-optmiality

  • 相关阅读:
    01-Git 及其可视化工具TortoiseGit 的安装和使用
    IntelliJ IDEA中Warning:java:源值1.5已过时, 将在未来所有发行版中删除
    JVM学习笔记四_垃圾收集器与内存分配策略
    JVM学习笔记三_异常初步
    CentOs7 图形界面和命令行界面切换
    基本概念一
    JVM学习笔记二_对象的创建、布局和定位
    JVM学习笔记一_运行时数据区域
    个人阅读作业二
    软件工程随笔
  • 原文地址:https://www.cnblogs.com/yrbbest/p/4438470.html
Copyright © 2011-2022 走看看