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

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

121. Best Time to Buy and Sell Stock【easy】

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: 5max. 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: 0In this case, no transaction is done, i.e. max profit = 0.

 

 解法一:

先看@keshavk 的解析和代码

We take prices array as [5, 6, 2, 4, 8, 9, 5, 1, 5]

In the given problem, we assume the first element as the stock with lowest price.
Now we will traverse the array from left to right. So in the given array 5 is the stock we bought. So next element is 6. If we sell the stock at that price we will earn profit of $1.

Prices:      [5, 6, 2, 4, 8, 9, 5, 1, 5]Profit:       Bought:5 Sell:6 Profit:$1 max profit=$1

Now the next element is 2 which have lower price than the stock we bought previously which was 5. So if we buy this stock at price $2 and sells it in future then we will surely earn more profit than the stock we bought at price 5. So we bought stock at $2.

Profit:      Bought:2     Sell:-              Profit:- max profit=$1

Next element is 4 which has higher price than the stock we bought. So if we sell the stock at this price.

Profit:      Bought:2     Sell:4 Profit:$2 max profit=$2

Moving further, now the next stockprice is $8. We still have $2 stock we bought previously. If instead of selling it at price $4, if we sell it for $8 then the profit would be $6.

Profit:      Bought:2     Sell:8 Profit:$6 max profit=$6

Now next stock is of $9 which is also higher than the price we bought at ($2).

Profit:      Bought:2     Sell:9 Profit:$7 max profit=$7

Now the next stock is $5. If we sell at this price then we will earn profit of $3, but we already have a max profit of $7 because of our previous transaction.

Profit:      Bought:2     Sell:5 Profit:$3 max profit=$7

Now next stock price is $1 which is less than the stock we bought of $2. And if we buy this stock and sell it in future then obviously we will gain more profit. So the value of bought will become $1.

Profit:      Bought:1     Sell:-              Profit:- max profit=$7

Now next stock is of $5. So this price is higher than the stock we bought.

Profit:      Bought:1     Sell:5 Profit:$4 max profit=$7

But our maximum profit will be $7.

1 public int maxProfit(int[] prices) { 2             int ans=0; 3             if(prices.length==0) 4             { 5                 return ans; 6             } 7             int bought=prices[0];                                 8             for(int i=1;i
bought)11 {12 if(ans<(prices[i]-bought))13 {14 ans=prices[i]-bought;15 }16 }17 else18 {19 bought=prices[i];20 }21 }22 return ans;23 }

 

解法二:

结合上面解法一的思路,重新简化代码

1 class Solution { 2 public: 3     int maxProfit(vector
& prices) { 4 int min_value = INT_MAX; 5 int max_value = 0; 6 7 for (int i = 0; i < prices.size(); ++i) { 8 min_value = min(min_value, prices[i]); 9 max_value = max(max_value, prices[i] - min_value);10 }11 12 return max_value;13 }14 };

写的过程中参考了@linjian2015 的代码

 

解法三:

public int maxProfit(int[] prices) {    int maxCur = 0, maxSoFar = 0;    for(int i = 1; i < prices.length; i++) {        maxCur = Math.max(0, maxCur += prices[i] - prices[i-1]);        maxSoFar = Math.max(maxCur, maxSoFar);    }    return maxSoFar;}

参考@jaqenhgar 的代码

The logic to solve this problem is same as "max subarray problem" using Kadane's Algorithm. Since no body has mentioned this so far, I thought it's a good thing for everybody to know.

All the straight forward solution should work, but if the interviewer twists the question slightly by giving the difference array of prices, Ex: for {1, 7, 4, 11}, if he gives {0, 6, -3, 7}, you might end up being confused.

Here, the logic is to calculate the difference (maxCur += prices[i] - prices[i-1]) of the original array, and find a contiguous subarray giving maximum profit. If the difference falls below 0, reset it to zero.

*maxCur = current maximum value

*maxSoFar = maximum value found so far

 

关于 Kadane's Algorithm 说明如下:

From Wikipedia, the free encyclopedia
 
Visualization of how sub-arrays change based on start and end positions of a sample. Each possible contiguous sub-array is represented by a point on a colored line. That point's y-coordinate represents the sum of the sample. Its x-coordinate represents the end of the sample, and the leftmost point on that colored line represents the start of the sample. In this case, the array from which samples are taken is [2, 3, -1, -20, 5, 10].

In computer science, the maximum subarray problem is the task of finding the contiguous subarray within a one-dimensional array of numbers which has the largest sum. For example, for the sequence of values −2, 1, −3, 4, −1, 2, 1, −5, 4; the contiguous subarray with the largest sum is 4, −1, 2, 1, with sum 6.

The problem was first posed by Ulf Grenander of Brown University in 1977, as a simplified model for maximum likelihoodestimation of patterns in digitized images. A linear time algorithm was found soon afterwards by Jay Kadane of Carnegie Mellon University (Bentley 1984).

 

A bit of a background: Kadane's algorithm is based on splitting up the set of possible solutions into mutually exclusive (disjoint) sets. We exploit the fact that any solution (i.e., any member of the set of solutions) will always have a last element i (this is what is meant by "sum ending at position i"). Thus, we simply have to examine, one by one, the set of solutions whose last element's index is 1, the set of solutions whose last element's index is 2, then 3, and so forth to n. It turns out that this process can be carried out in linear time.

Kadane's algorithm begins with a simple inductive question: if we know the maximum subarray sum ending at position i (call this  B_{i}), what is the maximum subarray sum ending at position i+1 (equivalently, what is B_{​{i+1}})? The answer turns out to be relatively straightforward: either the maximum subarray sum ending at position i+1 includes the maximum subarray sum ending at position i as a prefix, or it doesn't (equivalently, {\displaystyle B_{i+1}=max(A_{i+1},A_{i+1}+B_{i})}, where A_{i+1} is the element at index i+1).

Thus, we can compute the maximum subarray sum ending at position i for all positions i by iterating once over the array. As we go, we simply keep track of the maximum sum we've ever seen. Thus, the problem can be solved with the following code, expressed here in Python:

1 def max_subarray(A):2     max_ending_here = max_so_far = A[0]3     for x in A[1:]:4         max_ending_here = max(x, max_ending_here + x)5         max_so_far = max(max_so_far, max_ending_here)6     return max_so_far

Note: with a bit of reasoning you will see that max_so_far is equal to {\displaystyle max(B_{0},B_{1},B_{2},...,B_{i})}.

The algorithm can also be easily modified to keep track of the starting and ending indices of the maximum subarray (when max_so_far changes) as well as the case where we want to allow zero-length subarrays (with implicit sum 0) if all elements are negative.

Because of the way this algorithm uses optimal substructures (the maximum subarray ending at each position is calculated in a simple way from a related but smaller and overlapping subproblem: the maximum subarray ending at the previous position) this algorithm can be viewed as a simple/trivial example of dynamic programming.

The runtime complexity of Kadane's algorithm is  O(n).

 参考自:https://en.wikipedia.org/wiki/Maximum_subarray_problem

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

转载于:https://www.cnblogs.com/abc-begin/p/7623912.html

你可能感兴趣的文章
北航软院2013级C#期末考试部分考题解答
查看>>
CentOS 系统中安装 ArcGIS Server10.1 一些问题及解决
查看>>
asp.net里登陆记住密码
查看>>
【BZOJ】2190 [SDOI2008]仪仗队(欧拉函数)
查看>>
线性规划中的单纯形法与内点法(原理、步骤以及matlab实现)(一)
查看>>
简单DP【p2758】编辑距离
查看>>
Spring Data JPA:关联映射操作
查看>>
JWT入门简介
查看>>
结对编程——吐槽必应词典
查看>>
katalon系列八:Katalon Studio图片识别
查看>>
Spring操作指南-针对JDBC配置声明式事务管理(基于XML)
查看>>
sql server 调优----索引缺失
查看>>
spring + junit 测试
查看>>
.net core 无法获取本地变量或参数的值,因为它在此指令指针中不可用,可能是因为它已经被优化掉了...
查看>>
Poj2186Popular Cows
查看>>
TCP之listen&backlog
查看>>
实验室的毕业照
查看>>
核心编程答案(第六章)
查看>>
Spring 3.x jar 包详解 与 依赖关系
查看>>
java线程详解二
查看>>