Wednesday, October 9, 2019

1049. Last Stone Weight II

Oct. 9, 2019

Introduction


It is the algorithm for me to practice dynamic programming, and also it can be converted into classical algorithm called Knapsack algorithm. I had to spend extra few hours to study and then figure out the solution with more detail.


Case study


I added one more case study, and then look into challenge to prevent one stone to be counted more than once in any sum.

Here is my post.

Oct. 8, 2019 9:11 PM
It is the first submission I made by studying one of solutions written in Chinese. I still have several concerns in terms of implementation.
In order to fully understand the algorithm, I asked myself why the second for loop is looping from sum/2 to current variable value, can we do increasing order from current variable value to sum/2 instead. I changed the code, and then one of test cases fails.
I need to look into and be able to explain the above failed test case to change for loop from decreasing order to increasing order. I need to ask a few questions, and work on basics first.
I will come back and update the post based on better understanding of the algorithm.
Follow up on Oct. 9, 2019
I have to answer two questions in my knapsack solution, and argue that why my approach is correct.
Question 1:
The order does not matter. In my C# code, for (int i = 0; i < length; i++) , any order will work. Why?
Question 2:
In my C# code,for (int j = sum / 2; j >= current; j--), why it has to be in descending order in your for loop? Can we use ascending order from current to sum /2.
I think that if I can answer those two questions, I prove that I have a good understanding of my reasoning. Otherwise I just try to pass online judge, I studied the code but I could not figure out the same day.
My argument to answer the question 2 is that every stone can only be used once. So it has to be in descending order, otherwise one stone may be counted more than once to sum value.
My argument to answer the question 1 is hard to describe. I have to prove it using a generic case, give any sum = s1 + s2 + ... + si, each stone in right hand side will be consider once, and then assuming that 1, 2, ..., i is the order to show in the array, and then s1 will be marked true, next s1 + s2, ..., s1 + s2 + ...+si = sum is marked as true. That is all.
I also asked the question in the most popular discussion post here.
Follow up
Case study
In order to fully understand the algorithm, I asked myself why the second for loop is looping from sum/2 to current variable value, can we do increasing order from current variable value to sum/2 instead. I changed the code, and then one of test cases fails.
for (int j = sum / 2; j >= current; j--) => for (int j = current; j <= sum / 2; j++)
image
Given the array with values [31, 26, 33, 21, 40], the sum of the array is 151, let us denote it as Sum. Sum/ 2 will be 75. We can divide into two sets, [33, 40] and [31, 26, 21], the sum of first array is 73, and the sum of second array is 78, the minimum difference is 5.
But if we update the loop from ascending, one number may be used more than once, so that minimum difference can be one. Since [26, 26, 23] can be an array, but 26 is counted twice, the sum of the array is 75, so 151 - 2 * 75 = 1.
The following code passes online judge.
public class Solution {
    /// <summary>
        /// study code
        /// https://www.acwing.com/solution/LeetCode/content/2139/
        /// I like to read comment written in Chinese. I like to write good comment like this 
        /// as well one day. 
        /// (动态规划) O(n×sum)
        /// 合并的过程就是给每个重量前赋值正号或者负号的过程,相当于把这些石头分为两组,
        /// 使得两组的差值尽可能小,所以这是经典的集合划分NP完全问题,可以采用动态规划的方法求解。
        /// 设状态 f(i) 表示是否存在一个划分,使得某组的重量综合为 ii。
        /// 初始时 f(0)=true,其余为 false。
        /// 转移时,模仿01背包的算法,对于每个物品,有放和不放两种决策,故 
        /// f(j)=f(j)|f(j−stones[j])。
        /// 最终答案需要枚举,j 从 sum/2 开始到 0,如果 f(j)==true,则返回 sum−j−j。
        /// 时间复杂度
        /// 状态数为 O(n×sum),转移数为常数,故时间复杂度为 O(n×sum)。
        /// 空间复杂度
        /// 需要额外 O(n) 的空间构造堆。
        /// </summary>
        /// <param name="stones"></param>
        /// <returns></returns>
        public int LastStoneWeightII(int[] stones)
        {
            var length = stones.Length;
            var sum = stones.Sum();

            var found = new bool[sum + 1];
            found[0] = true;

            // transition formula - figure out the reasoning later
            for (int i = 0; i < length; i++)
            {
                var current = stones[i];
                for (int j = sum / 2; j >= current; j--)
                {
                    found[j] = found[j] | found[j - current];
                }
            }

            // Find maximum sum less and equal to sum/2. 
            for (int i = sum / 2; i >= 0; i--)
            {
                if (found[i])
                {
                    return sum - i - i; 
                }
            }

            return sum; 
        }
}


Tuesday, October 8, 2019

1012 Numbers with repeated digits

Oct. 8, 2019


Introduction


It is so surprise for me to read my own post over six months ago. There is a notification since one comment was added recently. I lost track on this algorithm on my github Leetcode repository page. 


One algorithm with 4 upvotes


I was so surprised to learn that I got 4 upvotes on this algorithm. It is such good learning experience for me to learn to write a good post. I like to write the solution again when I have 10 - 15 minutes break. 

March 21, 2019
1012. Numbers With Repeated Digits C# Study code from ranking No. 1 in weekly contest 128 (4 upvotes up to Oct. 8, 2019)
1012. Numbers With Repeated Digits C# standard depth first search with back tracking (1 upvotes up to Oct. 8, 2019)



Ranking board of discussion post



Here is the ranking based on number of upvote. It is a hard level algorithm. I wrote a post and then explained the top ranking weekly contest 128 No. 1, how his solution works and I wrote a C# solution with explanaton. Life is so interesting, I totally forgot what I did until some one left a comment on Oct. 8, 2019. 



Bill Nygren: 'A Stock That Doesn't Look Cheap on the Surface Might Be One of the Cheapest'

Here is the article.


1049 Last stone weight II - series 5 of 5

1049 Last stone weight II - series 4 of 5

1049 Last stone weight II - series 3 of 5

1049 Last stone weight II - series 2 of 5

1049 Last stone weight II - series 1 of 5

I like to look into classical algorithm called Knapsack algorithm. I like to work on a few easy level algorithms first, and then move on medium level algorithms.

I like to choose the post with most votes for me to study and then write a C# solution as well. Here is the link.


Bill Nygren: "Value Investing Principles and Approach" | Talks at Google

Here is the link.

William C. Nygren, CFA: Partner, Portfolio Manager and Chief Investment Officer - U.S. Equities Bill Nygren has been a manager of the Oakmark Select Fund (OAKLX) since 1996, Oakmark Fund (OAKMX) since 2000 and the Oakmark Global Select Fund (OAKWX) since 2006. He is also the Chief Investment Officer for U.S. Equities at Harris Associates, which he joined in 1983; he served as the firm’s Director of Research from 1990 to 1998. Mr. Nygren has received many accolades during his investment career, including being named Morningstar's Domestic Stock Manager of the Year for 2001. He holds an M.S. in Finance from the University of Wisconsin's Applied Security Analysis Program (1981) and a B.S. in Accounting from the University of Minnesota (1980).

Last stone weight II

I like to study one solution written in the blog, I will write a C# solution based on the idea.


Rochon – The Keys To Successful Equity Investments

Here is the article.

1) Consider stocks as fractional ownership in real businesses
2) Being present
3) Profit from market fluctuations rather than suffer from them
4) Leaving yourself a margin of safety
5) Stay within your circle of competence
6) Know when to sell
7) Learn from your mistakes
8) A constructive attitude



5) Stay within your circle of competence
To wander outside of your circle of competence significantly increases your probably of making a poor decision.  In the market, to realize better returns than others, you must have better knowledge regarding the value of the businesses in which you invest (the others are the market).

To succeed, it is important to stay close to companies that one can understand well and evaluate well."


1049. Last Stone Weight II

Here is my post written on Oct. 8, 2019

Oct. 8, 2019 9:11 PM
It is the first submission I made by studying one of solutions written in Chinese. I still have several concerns in terms of implementation.
In order to fully understand the algorithm, I asked myself why the second for loop is looping from sum/2 to current variable value, can we do increasing order from current variable value to sum/2 instead. I changed the code, and then one of test cases fails.
I need to look into and be able to explain the above failed test case to change for loop from decreasing order to increasing order. I need to ask a few questions, and work on basics first.
I will come back and update the post based on better understanding of the algorithm.
public class Solution {
    /// <summary>
        /// study code
        /// https://www.acwing.com/solution/LeetCode/content/2139/
        /// I like to read comment written in Chinese. I like to write good comment like this 
        /// as well one day. 
        /// (动态规划) O(n×sum)
        /// 合并的过程就是给每个重量前赋值正号或者负号的过程,相当于把这些石头分为两组,
        /// 使得两组的差值尽可能小,所以这是经典的集合划分NP完全问题,可以采用动态规划的方法求解。
        /// 设状态 f(i) 表示是否存在一个划分,使得某组的重量综合为 ii。
        /// 初始时 f(0)=true,其余为 false。
        /// 转移时,模仿01背包的算法,对于每个物品,有放和不放两种决策,故 
        /// f(j)=f(j)|f(j−stones[j])。
        /// 最终答案需要枚举,j 从 sum/2 开始到 0,如果 f(j)==true,则返回 sum−j−j。
        /// 时间复杂度
        /// 状态数为 O(n×sum),转移数为常数,故时间复杂度为 O(n×sum)。
        /// 空间复杂度
        /// 需要额外 O(n) 的空间构造堆。
        /// </summary>
        /// <param name="stones"></param>
        /// <returns></returns>
        public int LastStoneWeightII(int[] stones)
        {
            var length = stones.Length;
            var sum = stones.Sum();

            var found = new bool[sum + 1];
            found[0] = true;

            // transition formula - figure out the reasoning later
            for (int i = 0; i < length; i++)
            {
                var current = stones[i];
                for (int j = sum / 2; j >= current; j--)
                {
                    found[j] = found[j] | found[j - current];
                }
            }

            // Find maximum sum less and equal to sum/2. 
            for (int i = sum / 2; i >= 0; i--)
            {
                if (found[i])
                {
                    return sum - i - i; 
                }
            }

            return sum; 
        }
}


Actionable Items


It takes time to figure out the analysis how to come out the idea why using descending order is a must in second for loop. I had to go through rigorously thinking in order to understand the process. So I understand that it is time consuming process to figure out why.

Learning Knapsack algorithm turns into such great experience, since I try to challenge myself; try the different idea, failed test case, and then push myself to explain it. I could not explain it on Oct. 8, 2019. It turned out so clear to me next day.

François Rochon: "The Art of Investing: Analyzing Numbers and Going Beyond" | Talks at Google

Here is the link.


Monday, October 7, 2019

Case study: Mock interview as interviewer - 1049. Last Stone Weight II

Oct. 7, 2019

Introduction


I tried to solve the algorithm last Friday, but I failed to solve it. I only solved the easy level one last stone weight, so I decided to ask the interviewee in mock interview.

Case study


Here is the transcript.


Actionable Items 


I need to work on my weekly contest performance. I need to solve more algorithms, keep myself busy.

The interviewee has very good performance on weekly contest, his ranking is around 8000, mine is around 20,000 right now. He solved four algorithm in weekly contest 157, I only solved the first two algorithms, here is my blog. So I have to push myself solve more algorithms, keep myself active in practice.


Continue to work on algorithm and data structure

Oct. 7, 2019

Introduction


It is my short research. I like to figure out how to solve more algorithms in next two weeks. How can I do that?





Sunday, October 6, 2019

Laboratories of Democracy: what Seattle learned from having the highest minimum wage in the nation

Oct. 6, 2019

Introduction


It is interesting topic. I just had a road trip to the city of Seattle. My friend told me that the minimum wage is $15/ hour in the city of Seattle. I like to read more articles on this topic.

One article a time


Here is the article.

The city adopted a $15 minimum wage four years ago. Here’s what happened.


Bill Miller is staging one of Wall Street’s most closely watched comebacks

Here is the article.

Someone who invested $1,000 in the Value fund with Miller in 1993 earned more than $6,000 over the next decade, twice what they would have seen by investing in the S&P index.

There are two types of hedge funds, he says: those for people who want to stay rich and others who want to get rich. He wants to run the latter.

Miller is targeting one of the industry’s chief weakness — its high fees. Most hedge fund managers charge a 2 percent management fee and 20 percent of the profit earned, known as “2 and 20.” Miller allows clients to choose from several payment models, including paying him nothing if he doesn’t beat the S&P index.


Miller appears unfazed by the high-powered naysayers, comparing his investment in bitcoin to his once widely criticized investment in Amazon.
“People thought up until recently, less than three or four years ago, that Amazon was kind of a fake thing, too,” he said. “Now that’s flipped over, and people now think Amazon is going to kill every company in the country.

Bill Miller says his fund is off to a strong start in 2019, believes Amazon will double in three years

Here is the article.




How Investing Legend Bill Miller Is Beating the Market Again

Here is the article.

His optimism regarding a forthcoming market rebound is why he expects his top picks to outperform, including: Facebook Inc. (FB), ADT Inc. (ADT), Avon Products Inc. (AVP) and Amazon Inc. (AMZN), per MarketWatch.

Bill Miller's 4 Favorite Picks

(Company; Market Cap; YTD Stock Performance)

  • ADT; $5.4 billion,16.6%
  • Amazon; $816.9 billion, 8.1%
  • Avon; $876 million, 29%
  • Facebook; $428.2 billion; 12.3%


Bill Miller on Investing in Disruptive Technologies including Bitcoin

Here is the link.

Miller Value Partners’ Bill Miller holds the record for being the only mutual fund manager to beat the market for 15 years in a row. One way he did it is by investing in new technologies that the Wall Street establishment thought were crazy at the time - Amazon, Google and Facebook among them. His latest “crazy” idea: Bitcoin.

Legendary investor Bill Miller on Apple, Amazon and more

Here is the interview lasting 8 minutes.

Bill Miller, chairman of Miller Value Partners, sits down with CNBC's Brian Sullivan in an exclusive interview.

Bill Miller (investor)

Here is the wiki article.




Course 508: Great Investors: Others in the Hall of Fame Bill Miller

Here is the article.

Critics characterize Miller as a growth investor in a value investor's clothing, but a look into his thought process reveals Miller's knack for seeing value where others don't. This ability has allowed the Legg Mason Value Fund to beat the S&P 500 for over a dozen consecutive years--a remarkable feat.

A more recent example of Miller's value/growth mix is his purchase of Google GOOG, a rapidly growing Internet search engine. While many investors shied away from this stock due to valuation concerns, Miller scooped up shares during its IPO. The stock doubled quickly after the company went public. While it's still too early to tell where Google will be five or 10 years down the road, this purchase was done in classic Bill Miller fashion--investing in a wildly profitable company that few investors understand or appreciate. 


Course 505: Great Investors: Philip Fisher

Here is the link.


Course 505: Great Investors: Philip Fisher Fisher's 15 Points

Here is the article.

Fisher's investment philosophy can be summarized in a single sentence: Purchase and hold for the long term a concentrated portfolio of outstanding companies with compelling growth prospects that you understand very well.


MIT distributed system course

Oct. 6, 2019

Introduction


It is a good idea to spend some time to study the distributed system course. Here is the link.


Philip Fisher

Here is the article on investopedia.com.

Philip Fisher’s Belief in Small-Cap Growth Stocks

Fisher divided the universe of growth stocks into large and small companies. On one end of the spectrum are large, financially strong companies with solid growth prospects, which during his time included IBM, Dow Chemical and DuPont, all of which increased in share price fivefold in the 10-year period from 1946 to 1956.
Although such returns were enviable, Fisher was more interested in the big returns that could be found in "small and frequently young companies…[with] products that might bring a sensational future." Of these companies, Fisher wrote, "the young growth stock offers by far the greatest possibility of gain. Sometimes this can mount up to several thousand percent in a decade." Fisher believed that all else being equal, investors should concentrate their efforts on uncovering young companies with outstanding growth prospects.

Actionable Items

I should invest some time to learn to find some growth stocks to purchase with several thousand percent in a decade. 

COMMON STOCKS AND UNCOMMON PROFITS SUMMARY (BY PHILIP FISHER)

Here is the link.

Top 5 takeaways from Common Stocks and Uncommon Profits: 00:10 1. Fisher’s 15 points checklist 04:16 2. The Scuttlebutt method 06:40 3. Unconventional wisdom 1: Dividends don’t matter 09:32 4. Unconventional wisdom 2: You are diversifying too much 11:46 5. Fish in the right pond

- An investment should tic most of Philip Fisher’s 15 points checklist to be considered a great growth stock - Use “Main Street” resources, such as suppliers, customers, trade associations and former employees to beat Wall Street in the stock picking game - Look for companies that have great confidence in their businesses, where money is being reinvested in productive activities, rather than being dealt out in dividends - How to invest in stocks? Don’t diversify too much – the more companies you own, the less you know about each of them. - One of the most important investing strategies that you can learn about is filters. There are so many opportunities out there – but so little time.

ONE UP ON WALL STREET - PETER LYNCH - ANIMATED BOOK REVIEW

Here is the video.

"One Up On Wall Street" by Peter Lynch is one of the best books to read for anyone looking to invest and pick individual stocks.

Peter Lynch, managed the Fidelity Magellan Fund from 1977 to 1990, averaging a 29% annual rate of return for that time frame, making the Magellan Fund the top performing mutual fund in the world. This is one of the most readable and easy to understand investing books on the market. The lessons are simple, KNOW WHAT YOU OWN and don't let your emotions interfere with your decision making!


Peter Lynch On How To Pick Stocks

Here is one hour video.


Fox business - personal finance

Oct. 6, 2019

Introduction


I like to spend time to watch some videos from Fox business - personal finance. Here is the link.

ONE UP ON WALL STREET SUMMARY (BY PETER LYNCH)

Here is the video I like to watch.

In this video I will present the top 5 takeaways from One up on Wall Street, the bestselling book by legendary investor and manager of the Fidelity Magellan mutual fund, Peter Lynch.

Peter Lynch - Wikipedia

Here is the article I like to spend 10 minutes to read.

Case study: programmer as a career - series 4 of 4

Case study: 楼钧
无论正挤破头要去大厂的人,还是已经在光明顶沐浴阳光的人,程序员中的“老人”们已在寻找自己的下一个战场。因为对于绝大多数人来说,程序员不是一个终生职业。
“我现在转行了”,楼钧顿了顿说:“现在做餐饮。”放弃老本行,让在行业中小有名气的楼钧感到难为情。
楼钧是国内某大厂老人,40多岁,程序员出身。跟随技术趋势和公司业务的调整,他的职业生涯进行了几番变动,做过操作系统、云和大数据,几年前人工智能袭来时,他又要学习AI。直到这个时候,老楼承认这个年纪学新东西太吃力,那些书和论文已经啃不动了,离开是最好的选择,给年轻人挪窝,给自己解脱。
楼钧这样的人在他的老东家并不少见,他们在十几二十年职业生涯里,完成了财富积累后,隐退江湖。有趣的是,这其中一大波人选择了传统餐饮行业,这是个陈旧的古老行业,不需要翻英文论文,不需要一宿宿加班跟产品经理battle,一笔钱投进去,找个业内人,自己听响就够了。

Actionable Items

Case study: programmer as a career - series 3 of 3

Here is the article.
Case study: 
前百度资深研发工程师张成海
35岁后该怎么转型?这极富现代化的忧思不是一个新议题,但率先在程序员群体中蔓延。有调查显示,近一半的程序员年龄在25~29岁之间,且35岁以上占一成不到。
 
前百度资深研发工程师张成海认为,在国内,程序员的确不是一个终身职业。在他看来,这并不是因为程序员要掌握的技术日新月异,而是源于国内职场环境忽略了程序员的工程师属性。
 
有人认为程序员和医生不同,后者靠经验积累,前者则是靠吃青春饭,因为技术迭代的节奏太快,且每个技术都是不同的,需要重头再来。中年以后,程序员的学习能力和速度都极大下降,以致无法匹配工作需求,只能退出职场。
 
但张成海说,当下很多流行的技术其实是过去的延伸。他举例,Ruby on Rails 这个Web开发框架,现在基本已经消亡,但其中的思想在如今流行的Python Web框架Django中依然有所体现。不止如此,“现在所有流行的Web框架都会受到影响,一个美好的东西出来了,人类就会记住它,再以不同的形式重现它。”
 
“一个有素养的工程师不会被这些所谓的新东西迷惑。”张成海表示,前两年人工智能很火,诞生了很多新算法,但实际上,这些新算法不是凭空而来的,它们都是对旧有算法做出了各种改进,恰好在一段时间内集中爆发。有人说人工智能很新,他要从头学。这不能说明程序员不依靠经验,而是说明,国内公司分工有问题,没有提供一个好的职业发展途径。“国内注重的不是工程师的素养,而是能否加班,短期内能压榨多大的价值,有些程序员是速成的,知识体系本来就不牢固。”张成海解释到。
 

软件工程师落脚是在“工程师”,张成海笑言,对于工程师来说,经验总是凌驾于工具之上的,其他工程学范畴内适用,计算机同样适用。而国内程序员难以成为终身职业,根本原因是国内的资本发展不够健康,没有工会约束,最终忽略了程序员的工程师属性。

不过,仍有大量程序员在中年以后选择了更广泛的领域,好像前些年的程序员生涯是在练基本功,为后面更富色泽的人生打下一个基础。