Robinhood Stock Market Return of Investment Calculation Algorithm


You are given integers n, e, o, t. You have n dollars in principal that you invested in the stock market. Given the stock market alternates between first returning e and then o percent interest per year, return how many years it would take to reach at leastt dollars.

Example 1
Input
n = 100
e = 20
o = 10
t = 130
Output
2
Explanation
In the first year we earn interest of 20% and end up with $120.
In the second year we earn interest of 10% and end up with $132, which is above the target $130.

Algorithm of Robinhood Stock ROI

We update the current principal based on the year count. One pitfall is use 32-bit integer to accomodate for the current value which may overflow. You can use double or int64 to avoid the investment value overflow.

int robinhoodStockReturnOfInvestment(int n, int e, int o, int t) {
    int res = 0;
    double nn = n;
    while (nn < t) {
        if (res & 1) {
            nn = nn * ((100.0 + o) / 100.0);
        } else {
            nn = nn * ((100.0 + e) / 100.0);
        }
        res ++;
    }
    return res;
}

In Python, we don’t need to worry about the integer overflow.

class Solution:
    def robinhoodStockReturnOfInvestment(self, n, e, o, t):
        res = 0
        while n < t:
            if res & 1:
                n = n * (100 + o) / 100
            else:
                n = n * (100 + e) / 100
            res += 1
        return res

–EOF (The Ultimate Computing & Technology Blog) —

264 words
Last Post: Teaching Kids Programming - Check a Valid Parenthese String
Next Post: Teaching Kids Programming - Minimal Number of Brackets Needed to Make a Valid Parenthese String

The Permanent URL is: Robinhood Stock Market Return of Investment Calculation Algorithm (AMP Version)

Leave a Reply