2019-05-08 Final Review

Problem 1

Input

Binary tree T

Out

True if the tree is BST, False otherwise

Incorrect Solution

function Check(T):
    if T = null:
        return True
    return Check(T.left)
        and Check(T.right)
        and (T.key < T.right.key)
        and (T.key > T.left.key)

This is wrong because it only compares node with its direct children, but it doesn't check the grandchildren.

Idea

Check T.key > max(T.left) and T.key < min(T.right)

Solution

function Check2(T):
    if T = null:
        # return (True, -inf, inf)  # WRONG!!
        return (True, inf, -inf)
    res1, minl, maxl = Check2(T.left)
    res2, minr, maxr = Check2(T.right)
    res = resl and res r
        and T.key > maxl and T.key < minr
    _min = min(minl, minr, T.key)
    _max = max(maxl, maxr, T.key)
    return res, _min, _max

Complexity

Single Call: O(1)

number of calls = n + #Nulls \leq 3n

Total: 3nO(1)=O(n)

Exercise

CHECK IF RB-TREE

Stock Price

Input

Given stock prices P[1..n]

Output

Days to buy and sell to maximize profit given $1 fee for each day of owning the seock. Complexity O(n\log n)

Example

P = [1,3,3,4]

buy = 1
sell = 1
profit = 3 - 1 = 2

Divide & Conquer

From recursive call

  • buy&sell in 1st half
  • buy&sell in 2nd half

To consider

  • buy in 1st and sell in 2nd

if there is not $1 fee, the profit is max(P[n/2:]) - min(P[n/2])

max(P[k]-(k-n/2) | k from n/2+1 to n)
                +
max(-P[l]-(n/2-l) | l from 1 to n/2)

Solution

function SellBuy(P):
    if n = 1:
        return 0
    m = int(n/2)
    left = SellBuy(P[1..m])
    right = SellBut(P[m+1..n])
    middle = ...
    return max(left, right, middle)x
微信图片_20190508115656.jpg

Problem 3

Input

Array A[1..n] of numers and number C

Output

  • True if there are i and j such that A[i] + A[j] = C
  • False otherwise

Complexity: O(n\log n)

Steps

  1. Sort A
  2. For every i, search for (C-A[i])/2. If found return True
  3. return False

🚩 :triangular_flag_on_post:: do 2 in O(n)

Dream

For every i, search for (C-A[i])/2 in A[i+1..n]

  1. RB-tree T empty
  2. For every i from n to 1
    • search (C-A[i])/2 in T, return True if found
    • insert A[i] ino T
  3. return False

If we have no duplicates,
sort array of paris (A[i],i) by i

🚩 :triangular_flag_on_post:: What if we want to count # of such (i,j)

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容