Introduction to Algorithms No.7

Hello. Today, I have started Chapter 4, "Divide and Conquer." And I have learnt "The maximum-subarray problem."

Maximum-subarray algorithm can solve that problem. Suppose you have time series of stock prices, such as (5 10 4 2 3 7 1 5 6 2). You are at time 1 now. The stock price is 5 now. You know the future stock price (5 10 4 2 3 8 1 3 6 2). Then when will you buy the stock and sell it? The answer is, you should buy it at time 4 and sell it at time 6. Then you get 6.

I have written two codes, which run with different running time. One algorithm runs with Theta(n^2). The other runs with Theta(n*log(n)). Therefore, the latter runs faster. The two algorithms are as follows:

https://github.com/uriha421/introduction_to_algorithms/blob/master/I_Foundations/maximum-subarray_problem_slow.c

https://github.com/uriha421/introduction_to_algorithms/blob/master/I_Foundations/maximum-subarray_problem_fast.c

You will be surprised to recognize that the slow program is much simpler and shorter than the fast program!


The fast one is one of divide-conquer algorithms, which I have recently explained.

Calculating the running time needs mathematical analysis.


Thank you.


MEMO
Big O-notation determines the upper bound of the running time. Omega-notation determines the lower bound. Theta-notation determines the both.

Small o-notation of a function includes all functions that runs faster than the function for enough large n. If you find an algorithm that runs at Theta(f(n)), then you should find another algorithm that runs at o(f(n)).

Comments

  1. If I can know the price of the stock early, I will consider using your algorithm($_$). Unfortunately, I don't know much about the second algorithm, because the syntax of the c language is different from java. You are writing very well, I hope you have the time to teach me some c language.(this comment is translated by google translation from chinese to English)

    ReplyDelete

Post a Comment

Popular posts from this blog

Introduction to Algorithms No.1

Introduction to Algorithms No.10

Introduction to Algorithms No.5