博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
122. Best Time to Buy and Sell Stock II
阅读量:7080 次
发布时间:2019-06-28

本文共 1959 字,大约阅读时间需要 6 分钟。

题目:

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
   
 

链接: 

题解:

买卖股票,可以多次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

转载地址:http://iuvml.baihongyu.com/

你可能感兴趣的文章
SSPL的MongoDB再被抛弃,GUN Health也合流PostgreSQL
查看>>
知乎pure render专栏创办人@流形:选择React这条路,很庆幸
查看>>
修复.NET的HttpClient
查看>>
调查:Android的领先地位稳固
查看>>
在Maven项目中使用JUnit进行单元测试
查看>>
Docker发布应用程序指南
查看>>
你朋友圈里的广告是怎么做到合你胃口的?
查看>>
#第1天#《C Primer Plus》学习历程
查看>>
为什么说GraphQL可以取代REST API?
查看>>
亚马逊是如何进行软件开发的
查看>>
腾讯开源手游热更新方案,Unity3D下的Lua编程
查看>>
Kafka迎来1.0.0版本,正式告别四位数版本号
查看>>
Chef宣布100%开源,要走红帽模式?\n
查看>>
用实例讲解Spark Sreaming
查看>>
Visual Studio 15.8 Preview 3支持多点编辑功能
查看>>
我们究竟应不应该使用框架?
查看>>
如何用Kotlin Coroutines和Architecture Components进行Android开发?
查看>>
RxJava系列六(从微观角度解读RxJava源码)
查看>>
How do you create a DynamicResourceBinding that supports Converters, StringFormat?
查看>>
《快学 Go 语言》第 9 课 —— 接口
查看>>