Greedy
Last updated
Last updated
Greedy Algorithms can be adopted when a specific problem can be proofed that when locally optimal choice in each stages can produce a globally optimal choice. But in many problems, all stages is optimized does not means that it will be globally optimized.
Given n
non-negative integers a1, a2, ..., an
, where each represents a point at coordinate (i, ai)
. n
vertical lines are drawn such that the two endpoints of the line i
is at (i, ai)
and (i, 0)
. Find two lines, which, together with the x-axis forms a container, such that the container contains the most water.
Notice that you may not slant the container.
Example 1:
Constraints:
n == height.length
2 <= n <= 105
0 <= height[i] <= 104
If in Brute Force (暴力枚举) way, we can encount n * n
possibilities then calculate each area to get the max area.
Greedy Approach can optimize the complexity from $O(N^2)$ to $O(N)$
Let i
be the first line and j
be the last line.
For each pair of lines selected, the covered area size is A(i, j) = min(height_i, height_j) * (j - i)
.
If we move the longer line inner, min(height_i', height_j') <= min(height_i, height_j)
If we move the shorter line inner, min(height_i', height_j') > or <= min(height_i, height_j)
If the area will be larger, the contribution of updating lines will be positive.
Hence, we can only encount only n - 1
times then we can get the largest area.
Ref. https://leetcode-cn.com/problems/container-with-most-water/solution/container-with-most-water-shuang-zhi-zhen-fa-yi-do/
Status Transferring Tree
You are given an integer array prices
where prices[i]
is the price of a given stock on the ith
day.
On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day.
Find and return the maximum profit you can achieve.
Example 1:
Example 2:
Example 3:
Constraints:
1 <= prices.length <= 3 * 104
0 <= prices[i] <= 104
Consider two days
if the stock price of the next day is higher than today, buy it and sell it at next day.
in other circumstances, you can never earn more money.