Tuesday, July 5, 2022

Leetcode discuss: 465. Optimal Account Balancing

July 5, 2022

Here is the link. 

C# | Quick learner | DFS, backtracking | GraceMeng top voted

July 4, 2022
Introduction
It is ad hoc to learn one algorithm from top voted discuss posts from graceMeng. I chose to study this hard level algorithm. I just quickly read the analysis and then studied one of C# discuss post.

GraceMeng -> top voted discuss algorithms
Leetcode newly release product feature: Leetcode profile -> discuss -> Most voites -> top 15 algorithms (https://leetcode.com/GraceMeng/). I choose to study those algorithms and figure out what is the secret in the analysis to win so many up-votes.

image

Ideas | Analysis from graceMeng | Top-voted one
I like to learn how to write a good analysis from graceMeng - https://leetcode.com/problems/optimal-account-balancing/discuss/130895/Recursion-Logical-Thinking.

? what does it mean to settle the debt
nobody owes others

? how do we represent how much money a person owes others
We build current debt situation debt[], e.g. debt[i] = 10 means a person owes others 10

? how do we settle one's debt
assuming [0, curId - 1] has been settled,
for debt[curId],
any curId + 1 <= i <debt.length such that debt[i] * debt[curId] < 0 can settle it

state
The next account to balance, curId, can uniquely identify a state
state function
state(debt[], curId) is the minimum transactions to balance debts[curId...debtLength - 1] such that debts[0...curId-1] are balanced.
goal state
state(initial debt[], 0)
state transition
now: state(debt[], curId)
next: state (debt[] after balance curId, curId + 1)

state(debt[], curId) = 1 + min(state (debt[] after balance curId, curId + 1))

Note

  • How do we decide who can balance the account of curId?
    There are many people who can balance curId's account -- person i behind curId with debt[i] * debt[curId] < 0.

C# code implmentation -> backward -> Analysis
I think that it is easy for me to understand the algorithm by reading the following C# code. The DFS search and also brute force comparison among all options in order to get the minimum transaction.

I like to talk about a test case, and then discuss my concerns. Through the discussion, I can learn how to prototype the algorithm to this classical approach.

Example 1:
Input: transactions = [[0,1,10],[2,0,5]]
Output: 2
Explanation:
Person #0 gave person #1 $10.
Person #2 gave person #0 $5.
Two transactions are needed. One way to settle the debt is person #1 pays person #0 and #2 $5 each.

By going through transactions, there are three people, [0, 1, 2].
Next it is to calculate debt[] for each person.
First transaction: [0, 1, 10], we have the following facts:
debt[0] = -10,
debt[1] = 10

Second transaction: [2, 0, 5], and then we have updates:
debt[2] = -5
debt[0] = -10 + 5 = 5.

So debt[] = int[]{5, 10, -5}

Next is the exercise how to apply DFS search and get minimum transaction.
It is easy to figure out one of minimum count (minimum count is 2) of transactions is to let person 1 to pay person 0 with 5 dollars, and then person 1 to pay person 2 5 dollars.

Now my suggestion is to go back to the above analysis, and then combine the test case I just warm up, and then try to figure out what is truth in the above analysis.

Leave for my practice privately if I have time.

The following C# code passes online judge.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _465_optimal_account_balancing
{
    class Program
    {
        static void Main(string[] args)
        {
            var transactions = new int[2][];
            transactions[0] = new int[] { 0, 1, 10 };
            transactions[1] = new int[] { 2, 0, 5 };

            var result = MinTransfers(transactions);
            Debug.Assert(result == 2);
        }

        /// <summary>
        /// code study
        /// https://leetcode.com/problems/optimal-account-balancing/discuss/130895/recursion-logical-thinking
        /// One of replies - C# solution shared by pantigalt
        /// </summary>
        /// <param name="transactions"></param>
        /// <returns></returns>
        public static int MinTransfers(int[][] transactions)
        {
            var debt = CreateDebtTable(transactions);
            return CalculateMinTransfers(0, debt);
        }

        /// <summary>
        /// It is hard for me to figure out, so I just learn quickly by studying GraceMeng's one
        /// </summary>
        /// <param name="curId"></param>
        /// <param name="debt"></param>
        /// <returns></returns>
        private static int CalculateMinTransfers(int curId, int[] debt)
        {
            // skip all account with zero balance
            while (curId < debt.Length && debt[curId] == 0)
            {
                curId++;
            }

            // Everyone has zero balance
            if (curId == debt.Length)
            {
                return 0;
            }

            // Everyone before current person has zero balance
            // current person has non-zero balance
            int minTransactions = int.MaxValue;
            for (int i = curId + 1; i < debt.Length; i++)
            {
                // check for opposite signs
                if ((debt[i] ^ debt[curId]) < 0)
                {
                    // modify debt for current person
                    debt[i] += debt[curId];

                    // recursive think -> DFS -> minimum transactions -> ?
                    minTransactions = Math.Min(minTransactions, CalculateMinTransfers(curId + 1, debt) + 1);

                    // restore debt for current person
                    debt[i] -= debt[curId];
                }
            }

            return minTransactions;
        }

        /// <summary>
        /// Lynq expression: 
        /// Dictionary<int, int> -> debts.Select(x => x.Value).ToArray();
        /// </summary>
        /// <param name="items"></param>
        /// <returns></returns>
        private static int[] CreateDebtTable(int[][] items)
        {
            // accumulate debts with original person ids
            var debts = new Dictionary<int, int>();

            foreach (int[] item in items)
            {
                if (!debts.ContainsKey(item[0]))
                {
                    debts.Add(item[0], 0);
                }

                if (!debts.ContainsKey(item[1]))
                {
                    debts.Add(item[1], 0);
                }

                debts[item[0]] += item[2];
                debts[item[1]] -= item[2];
            }

            // we need to return an array with sequential person ids
            return debts.Select(x => x.Value).ToArray();
        }
    }
}

Monday, July 4, 2022

Air Canada | Second quarter 2022

Why Air Canada Stock Plunged 28% in June

Jitendra Parashar    Published 

Here’s why Air Canada stock tanked by nearly 28% in June, extending its second-quarter losses to 34%.

What happened?

Air Canada (TSX:AC) stock plunged by nearly 28% in June to $16.04 per share, marking its worst monthly losses since March 2020 and second worst monthly performance in five years. AC stock continued to fall in all three months of the second quarter, which took its quarterly losses to nearly 34% against the TSX Composite Index’s 13.8% drop in Q2.

So what?

Last month’s big losses in the shares of Air Canada could be attributed to the recent macro-level and airline industry-wide concerns. As inflationary pressures continue to haunt investors across North America, the U.S. Federal Reserve hiked its key interest rate by 0.75 percentage points in June — its steepest rate hike since 1994. The Fed also signaled more aggressive monetary policy moves in the coming months.

While central banks’ aggressive approach in the U.S. and Canada might help them fight inflation in the medium term, investors fear that these moves could drive the economy into a recession. In times of a recession, people tend to cut their discretionary expenditures, including air travel. That’s one of the key reasons why concerns about a looming recession drove a massive selloff in Air Canada stock in June.

Now what?

Air Canada stock continues to be among the worst performing TSX stocks since 2020. The global pandemic-driven shutdowns badly affected the Canadian flag carrier’s financial growth in 2020, driving its shares down by 53% that year. While investors expected the air travel demand to recover sharply in 2021, new COVID variants forced authorities to extend travel restrictions. That’s why instead of posting a recovery, AC stock fell by another 7.2% in 2021.

In the first quarter of 2022, early signs of improving air travel demand helped Air Canada regain investors’ confidence, which drove its stock higher by nearly 15% in Q1. However, factors like rising geopolitical tensions, skyrocketing jet fuel prices, inflationary pressures, and the possibility of a recession turned Air Canada stock negative again in Q2. As a result, it currently trades with more than 24% year-to-date losses. While the largest Canadian passenger airline company continues to adjust its operations in expectation of higher demand, these efforts might not lead to a sustainable financial recovery if a recession hammers the demand again. Given that, Air Canada stock could continue to struggle in the near term.

Canada tech sector | Layoffs looms

HARD TIMES COMING FOR CANADA’S TECH SECTOR AS WAVE OF LAYOFFS LOOMS


  1. Wealthsimple Technologies Inc
  2. Thinkific Labs Inc.
  3. Legible Inc., an online e-book marketplace
  4. Goodfood Market Corp

 The technology sector in Canada is about to suffer the biggest hit that will lead to hard times. This comes after a growing wave of layoffs and hiring freezes in the American tech sector. According to industry watchers, this will soon affect Canada. They warn that although job cuts are already happening in the country, bigger reductions are yet to come. Currently, the message going around to businesses is basically to protect their capital, as many more layoffs are yet to come. The statement came from Jacques Bernier, a Managing Partner with Montreal’s “fund-of-funds” firm Teralys Capital.

THE UPCOMING CRISIS IN CANADA’S TECH SECTOR MAY BE EVEN WORSE THAN IN 2008

According to a billionaire Vancouver investors, the upcoming situation will bring a massive “bloodbath”. The investor and entrepreneur Markus Frind, who owns a majority of online furniture seller Cymax Group Inc. and backs several venture capital firms are very pessimist about the situation. Apparently, all companies inside the group need to review their spending plans. Apparently, the upcoming economic recession will be way worse than 2008, when the credit crisis sparked a recession.

The Canadian bank Wealthsimple Technologies Inc. has been part of the wave of companies with frozen job hiring. Furthermore, an online platform for course creators, Thinkific Labs Inc. announced deep staff cuts this spring. The same was adopted by Legible Inc., an online e-book marketplace. Both companies are part of the Canadian Exchanges. Another company in the tech sector is Goodfood Market Corp. already cut 2.8 percent of its 2,500+ jobs.

MORE LAYOFFS ARE YET TO COME IN CANADA

In addition to these companies, several other fast-growing Canadian tech companies have quietly cut jobs in 2022. They are definitively preparing for a major downturn in the coming months. The ongoing global inflation moved by several factors such as diseases and the war is certainly a determining factor behind the upcoming crisis.

The cuts are just an initial measure or a preview. Apparently, portfolio companies are also considering layoffs, and “reductions in the workforce” in the coming months. As aforementioned, the layoffs are part of an initial measure, or better saying cost-saving cost-preventing methods. The situation has been more evident in the United States. Several unprofitable tech companies are reducing their cash spent. This cash usually comes from bigger investors.

There are bold promises coming for Canada, such as the speculated Tesla factory. However, only time will tell if the situation will improve. The country recently stole the headlines after deciding the ban Huawei-related 5G technologies.


Sunday, July 3, 2022

Calgary condo: July 3, 2022

 2405, 4641 128 Avenue NE 2405, Calgary, Alberta, T3N1T2

$236,000 CAD

Property Summary for 2405, 4641 128 Avenue NE

Type
 
Single Family
Sub-Type
 
Condominium/Strata
Style
 
High rise
Building Type
 
Apartment
Title
 
Condominium/Strata
MLS® Number
 
A1216653
Year Built
 
2020
Stories
 
6
Basement
 
Unknown
Association Fee
 
$276.76 CAD
Neighborhood
 
Skyview Ranch
Postal Code
 
T3N1T2

Description for 2405, 4641 128 Avenue NE

Opportunity for Investers or First-time buyers. Beautiful Apartment in the community of Skyview Ranch NE. Amenity rich Building. Free GYM Access and Party room. Day Care Facility on site. Amazing layout, FOURTH level Unit, Low Condo Fee includes various services. 2 LARGE BEDROOMS & 2 FULL BATH. Currently rented & renters willing to stay. Great Revenue Property. Heated Underground Parking, Cozy Living /Dinning room combination. Beautiful Kitchen with Granite counters & breakfast bar. IN UNIT stacked Laundry machines. Living room opens into patio with small green space at the back. Granite counters in washrooms. 8' feet high ceiling, provides more air and space. Plenty of Visitor parking stalls. Right Across the building, FUTURE LRT/TRAIN Station. Several amenities within few minutes distance. This beautiful unit could be your home, act fast. (id:1937)


Calgary condo - July 3, 2022

 103, 19661 40 Street SE 103, Calgary, Alberta, T3M3H3

$219,000 CAD


Rooms

Room NameLocationWidthLength
4pc BathroomMain level7.75 Ft4.92 Ft
KitchenMain level8.50 Ft10.50 Ft
Laundry roomMain level3.00 Ft3.58 Ft
Living roomMain level17.42 Ft10.50 Ft
Primary BedroomMain level10.17 Ft9.08 Ft
OtherMain level5.08 Ft9.25 Ft

Description for 103, 19661 40 Street SE

This is not just a home, it's a lifestyle! If you're looking for a modern 1-bedroom apartment to call your own, look no further! This 1 bed 1 bath apartment has everything you need and more. The open floor plan is perfect for entertaining guests and the large kitchen island provides plenty of extra space to cook up your favorite meals. This elegant home has been incredibly well kept and shows like new. Youll be impressed by the modern styling and updated fixtures, including stainless steel appliances, granite counter tops, sleek lighting throughout, and upgraded built ins. The home is situated in the newly developed community of Seton, with excellent transport links and a close proximity to all amenities and the south health campus. A rare gem! (id:1937)

Stories
 
4
Basement
 
Unknown
Association Fee
 
$201.82 CAD
Neighborhood
 
Seton

Postal Code
 
T3M3H3

Property Summary for 103, 19661 40 Street SE

Type
 
Single Family
Sub-Type
 
Condominium/Strata
Building Type
 
Apartment
Title
 
Condominium/Strata
MLS® Number
 
A1233966
Year Built
 
2020


Condo in Calgary | July 3, 2022

408, 355 Taralake Way NE
Calgary, Alberta T3J0M1

MLS® Number: A1235491 

4 hours ago

$219,900

Description

TOP FLOOR UNIT! DOWNTOWN AND MOUNTAIN VIEWS! LARGE WINDOWS ALLOW FOR LOTS OF NATURAL LIGHT INTO THE HOME! Located in the heart of Taradale, this unit has multiple access routes! Offering close to 700 SQ FT of Luxurious Living Space with Quality Finishing! Simple and functional Open Floorplan Concept! Awesome usage of living space! Entering the unit, you will find a dining, kitchen with granite countertops and stainless steel appliances, family room with access to your balcony, 2 bedrooms and a FULL bath. The master has a W.I.C and direct access to the FULL bath! LAUNDRY IS IN UNIT! Easy Access to parks, playgrounds, bus stops, schools and shopping. Easy access to LRT, Genesis Centre and Saddletown Circle as well! AMAZING LOCATION! GORGEOUS UNIT! GREAT VALUE! (25852617)

Property Summary

Property Type
Single Family
Building Type
Apartment
Storeys
4
Community Name
Taradale
Subdivision Name
Taradale
Title
Condominium/Strata
Land Size
Unknown
Built in
2013
Annual Property Taxes
$1,133
Total Parking Spaces
1
Time on REALTOR.ca
4 hours

Saturday, July 2, 2022

Linkedin profile: Quishon Walker | Layoff from TESLA | Good advice

Here is the link.  

I like to read more about layoff, at will, and all other good topics. 

Welcome to the real world. Employers create jobs to fill a need THEY have, not to meet YOUR needs. If you want employment you cannot be terminated from, risk everything and go out and create your own employment. Start a business. If you reach a certain level of success, you will realize that you have a need for employees, and at that time, you must weigh your need against the cost of paying to fill that need. When you see that the benefits outweigh the costs, you will hire if not you won't.

What is so hard to understand there? It is "at will" employment. You can leave any time you want.

Celeb Brown

Its amazing the amount of people here who dont read before replying or research the article.

1: He agreed to a work contract at hiring to fill the role Tesla needed him to fill.

2: He refused an email to return to work FROM THE CEO.

3: He originally wasnt on the layoff list as evidenced by Tesla calling him into work.

Its easy to join someones emotional response, but the Logic and Facts of this are clear regardless of how you all feel. He refused the CEOs call to work. When you refuse to fulfill contractual obligations in your job, you are eligible for layoffs.

It is regrettable he gave up his future like this, but this easily could have been avoided by one reply: "Yes. Ill gladly come in and work." Boom. He would still be making 6 figures, driving 2 Teslas and vacationing in Rome. Never refuse a call to return to work if you contractually agreed.