Dynamic Programming

Dynamic Programming is a rage in interviews these days, not many get to use them in their daily programming lives, though.

In Dynamic Programming the idea is simple – if you have counted a million items in a basket and if somebody added another item to the basket then the no of items in the basket currently is a million+1. You do not recount again, just add to the work you already did. You build solutions for problems using solutions for the sub-problems.

Here’s a sample problem from LeetCode.

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Example 1:
Input: [7, 1, 5, 3, 6, 4]
Output: 5

max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
Example 2:
Input: [7, 6, 4, 3, 1]
Output: 0

In this case, no transaction is done, i.e. max profit = 0.


class Solution {
    public int maxProfit(int[] prices) {
        int currentMaxProfit = 0,
            currentMinPrice = prices.length>0?prices[0]:0;

        for (int i=1; i<prices.length; i++) {
            currentMaxProfit =
                Math.max(currentMaxProfit, prices[i] - currentMinPrice);
            currentMinPrice = Math.min(currentMinPrice, prices[i]);

        return currentMaxProfit;

As you can see, the minimum price is not recomputed by scanning all elements of the array from start to current element – 1 to compute max profit for the current element – converting this algorithm to an O(n) from O(n*n).

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s