Site Search:
Showing posts with label dynamic programming. Show all posts
Showing posts with label dynamic programming. Show all posts

Best Time to Buy and Sell Stock

Problem:


Best Time to Buy and Sell Stock

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 (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

Example 1:

Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 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
Explanation: In this case, no transaction is done, i.e. max profit = 0.

Solution:

The brutal force approach is for each day, we iterate all the elements on its right and find the max value to calculate a profit. Finding the max value cost O(N) calculation, and since we need to calculate a profit for each day in order to find global maximum, the time complexity is O(N^2). We can apply dynamic programming to get a solution with O(N) time complexity. Instead of processing array elements from left to right, we exam the array element from right to left, and we record for each day, what is the best sell price we saw so far. Eventually, we will get an array that able to return us the best sell price for each day with cost O(1). With this array ready, we iterate the original array from left to right, use best sell price minus the buy price for that day, then get a profit. Finally, we found the global maximum profit.

class Solution {
  public static void main(String...args) {
    int[] arr = new int[]{7,1,5,3,6,4};
    int profit = solve(arr);
    System.out.println(profit);
  }

  public static int solve(int[] arr) {  //7,6,4,3,1
    if(arr.length < 2) return 0;
    int[] sellMax = new int[arr.length];    //7,6,4,3,1
    sellMax[arr.length - 1] = arr[arr.length - 1];
    for(int i = arr.length - 2; i >= 0; i--) {
      sellMax[i] = Math.max(arr[i], sellMax[i + 1]);
    }
    int profit = 0;
    for(int i = 0; i < arr.length; i++) {  //5
      profit = Math.max(profit, sellMax[i] - arr[i]);
    }
    return profit;
  }
}

Since we iterate the array twice, the time complexity is O(N), we need an extra array to store the best sell price for each day, the space complexity is O(N) as well.


Number of Submatrices That Sum to Target

Problem:

Given a matrix, and a target, return the number of non-empty submatrices that sum to target.

For example, given matrix
{
{0, 1},
{0, 1}
}
and target 0, the output should be 3.
Given the same matrix and target 1, the output should be 4.
Given the same matrix and target 2, the output should be 2.
Given the same matrix and target 3, the output should be 0.

Solution:
We have solved Subarray Sum Equals K before, this problem can be converted to that problem then get solved. The matrix involved in Subarray Sum Equals K is a 1D array, while we are dealing with 2D array here.

We can calculate the prefix sum of the original array, then any submatrices' sum can be calculated with from the prefix sum matrix. curr_sum = sum[r2][col] - sum[r1 - 1][col]. In 2D the prefix sum is a sum of the current value with the integers above or on the left.

prefix sum
For example:

              0 0 0
0 1         0 0 1
0 1         0 0 2


Now we can write the code

import java.util.*;
class Solution {
  public static void main(String...args) {
    int[][] arr = new int[][]
                            {
                            {0, 1},
                            {0, 1}
                            };
    int target = 0;
    System.out.println(numOfsubArrays(arr, target));
    target = 1;
    System.out.println(numOfsubArrays(arr, target));
    target = 2;
    System.out.println(numOfsubArrays(arr, target));
    target = 3;
    System.out.println(numOfsubArrays(arr, target));
  }
 
  public static int numOfsubArrays(int[][] arr, int target) {//0
    int r = arr.length;   //2
    int c = arr[0].length;  //2
    int[][] sum = new int[r+1][c+1]; //sum matrix is bigger than the orginal max
    //fill the sum from index 1,1 to r,c, not filled cells remain 0.
    for(int i = 1; i < r+1; i++) {
      for(int j = 1; j < c+1; j++) {
        sum[i][j] = sum[i-1][j] + sum[i][j-1] - sum[i-1][j-1] + arr[i-1][j-1];
      }
    }
    /*
    0 0 0
    0 0 1
    0 0 2
    */
    int count = 0;
    Map<Integer, Integer> vals = new HashMap<>();
    for(int i = 0; i < r; i++) {
      for(int j = i+1; j < r+1; j++) {
        //with fixed row, 2D Subarray Sum Equals K problem converts to 1D Subarray Sum Equals K
        vals.clear();
        for(int k = 0; k < c+1; k++) {  //k=0, so we can have val.put(0, 0)
          int delta = sum[j][k] - sum[i][k];
          count += vals.getOrDefault(delta - target, 0);
          vals.put(delta, vals.getOrDefault(delta, 0) + 1);
        }
      }
    }
    return count;
  }
}


The time complexity is O(RRC) for the 3 layered loop, the space complexity is O(RC) for the prefix sum matrix.

see also:
Subarray Sum Equals K

Sliding Window Maximum

Problem:

Given an integer array and an Integer k, k represents a sliding window with size k that starts at the array's left end, moves one step at a time until reaches the array's right end. Each time the sliding window moves, it brings in a new number from right and removes an old number at left. Return an array which contains the max number in the sliding window at each move.

For Example:

Given array [1,3,-1,-3,5,3,6,7], and k = 3
The output is: [3,3,5,5,6,7]
Explanation:

Window position                Max
---------------               -----
[1  3  -1] -3  5  3  6  7       3
 1 [3  -1  -3] 5  3  6  7       3
 1  3 [-1  -3  5] 3  6  7       5
 1  3  -1 [-3  5  3] 6  7       5
 1  3  -1  -3 [5  3  6] 7       6
 1  3  -1  -3  5 [3  6  7]      7

 1 <= k <= array.length

Solution:

The brutal force solution is search k elements for the max at each array index from 0 to n - k. The time complexity will be nk.

There is a time complexity O(N) solution if we redesign the problem.

We can divide the original array into k sized chunks. When the k sized sliding window slides through the array, the chunk's boundary will cut the window into 2 parts. The original problem of finding the max value in the sliding window is converted to find the max value for the left half, max value for the right half, then combine the 2 max values we can find the max value in the sliding window.

imaginary boundary cut the k sized sliding window into 2 halves


With the imaginary k sized boundary added, the rest of the work is easy. In order to find the max value for the left half of the sliding window, we only have to scan from the boundary leftward, for the max value for the right half of the sliding window, we only have to scan from the boundary rightward. We can scan these max values and store them in array left and right. Then we can iterate the original array, use the pre-scanned left and right max value arrays to find the left half and right half's max values. 

import java.util.*;
public class Solution {
  public static int[] maxNum(int[] arr, int k) {
    int n = arr.length;
    int[] result = new int[n - k + 1];
    int[] left = new int[n];
    int[] right = new int[n];
    left[0] = arr[0];
    right[n - 1] = arr[n - 1];
    for(int i = 1; i < n; i++) {
      //left -> right
      if(i % k == 0) {
        left[i] = arr[i];  //reset max at boundary
      } else {
        left[i] = Math.max(left[i - 1], arr[i]);  //compare with left
      }
      //right -> left
      if((n - i) % k == 0) {
        right[n - i - 1] = arr[n - i - 1];  //reset max at boundary
      } else {
        right[n - i - 1] = Math.max(right[n - i], arr[n - i - 1]); //compare with right
      }
    }
    for(int i = 0; i <= n - k; i++) {
      result[i] = Math.max(right[i], left[i + k - 1]);  //right[i] is the max value of the sliding window's left half
    }
    return result;
  }
 
  public static void main(String...args) {
    int[] arr = new int[]{1,3,-1,-3,5,3,6,7};
    for(int i : maxNum(arr, 3)) {
      System.out.print(i + " ");
    }
  }
}

We need to iterate the array once to generate the max value array left and right, we need to iterate the array the second time to calculate the sliding window's left and half max value, then combine them to find the max value in the sliding window. The time complexity is O(N), the space complexity is O(N) because of the left and right array for max values.

Trapping Rain Water

Problem:

Given a non-negative integer array. Each element represents an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.

For example, given array [1,4,0,1,0,3,1,2,0,1], the elevation map represented by it can trap 10 units of rain water.

Solution:

The brutal force solution is find the water above each of the bars. For a given bar, we can find the max bar height on the left lBound and the max bar height on the right rBound, then the amount of water above the current bar is the min(lBound, rBound) - currentHeight. For each bar, we can search the other n -1 bars to find the lBound and rBound, the total time complexity is O(N^2) and space complexity is O(1).

An improvement on the brutal force is to trade space for time. At index i, if we know the max bar height on the left is lMax[i], at index i+1, we don't have to search again, we just have to use formula lmax[i] = Math.max(lMax[i-1], height[i]) 
where i from 1 to height.length - 1. 
We can say the same to the rMax, 
rMax[i] = Math.max(rMax[i], height[i+1]) 
where i from arr.length - 2 to 0
That way, we get O(N) time complexity, but space complexity is O(N) as well.

With similar approach used in Largest Rectangle in Histogram, we can use a stack to follow the height values' changing trend, once we find the turning point, we take actions accordingly. In this case, we use the stack to store the decreasing sequence of the height. Once the current bar's height increase, we know we just passed a valley. The 2 bars at the stack top and the current bar formed a valley, the water holding capacity of this valley is (Math.min(height[stack(top-1)], height[current])) - height[stack(top)]) * (current - stack(top)).

import java.util.*;
public class Solution {
  public static int trap(int[] arr) {
    int water = 0;
    Stack<Integer> lMax = new Stack<>();
    lMax.push(0); //1 5 6
    for(int i = 1; i < arr.length; i++) { //5
      while(!lMax.isEmpty() && arr[lMax.peek()] <= arr[i]) {
        int index = lMax.pop();
        if(lMax.isEmpty())
          break;
        water += (Math.min(arr[lMax.peek()], arr[i]) - arr[index]) * (i - lMax.peek() - 1);
      }
      lMax.push(i);
    }
    return water;
  }
  public static void main(String...args) {
    int[] arr = new int[]{1,4,0,1,0,3,1,2,0,1};
    System.out.println(trap(arr));
  }
}

The time complexity is O(N) and the space complexity is O(N) due to the stack.

There is a O(N) time complexity and O(1) space complexity solution.
The intuition is: we can use two pointers to mark a water container with left and right edges. The left pointer start at index 0 and the right pointer start at the last index. The two bars pointing by the 2 pointers formed a water container with capacity bottleneck at the shorter one. The 2 pointers move inward searching for the longer bars as the container's edges. If a bar is shorter than the bottleneck, the bar can hold water. If a bar is longer than the shorter container edge, the pointer moves to it thus form a taller but narrower container.

public class Solution {
  public static int trap(int[] arr) {
    int water = 0;
    int lBound = arr[0];
    int rBound = arr[arr.length - 1];
    int i = 0;
    int j = arr.length - 1;
    while(i < j) {
      if(lBound < rBound) {
        while(arr[i] <= lBound) {
          water += lBound - arr[i];
          i++;
        }
        lBound = arr[i];
      } else {
        while(arr[j] <= rBound) {
          water += rBound - arr[j];
          j--;
        }
        rBound = arr[j];
      }
    }
    return water;
  }
  public static void main(String...args) {
    int[] arr = new int[]{1,4,0,1,0,3,1,2,0,1};
    System.out.println(trap(arr));
  }
}


See also:


Unique Binary Search Trees

Problem:

Given an integer n, return how many unique BST's (binary search trees) with values 1, 2, 3 ... n.

For Example:

Given integer: 3
Answer: 5
Explain:
The unique BSTs with values 1 2 and 3 are the following 5:

   1         3     3      2      1
    \       /     /     / \      \
     3     2    1      1   3      2
    /     /       \                   \
   2     1         2                   3

Solution:

Given 1 2 3, we have 3 choices for the root node. The root node can be the element at index i from 0 to 2, each choice will give us a new group of new BSTs. The number BST created by each choice is marked as F(n, i). So the total number of unique BSTs is the following:
G(n) = Sum(F(n, i))
where i range from 0 to n-1.
For a given F(n, i), the root node i divide the 1 to n array into left and right subtree. The left subtree has i - 1 elements, the right tree has n - i elements. 
Left half has G(i - 1) possible choices, the right half has G(n - i) choices,
So F(n, i) = G(i - 1)*G(n - i)
Finally, our formula is:
G(n) = Sum(G(i - 1)*G(n-i)) where i range from 1 to n.

We already know the base Case 
G(0) = 1
G(1) = 1
What's left is use dynamic programming to find the G(2), G(3) .... G(n).

class Solution {
  public static void main(String...args) {
    System.out.println(enumerate(3));
  }
  public static int enumerate(int size) {
    int[] g = new int[size + 1];
    g[0] = 1;
    g[1] = 1;
    for(int n = 2; n <= size; n++) {
      for(int j = 1; j <= n; j++) {
        g[n] += g[j-1]*g[n-j];
      }
    }
    return g[size];
  }
 
  private static class Node {
    int value;
    Node left;
    Node right;
    public Node(int value, Node left, Node right) {
      this.value = value;
      this.left = left;
      this.right = right;
    }
  }
}

There are 2 for loops, so the time complexity is O(N^2). We store the middle value of G(i) where i ranges from 0 to n. So the space complexity is O(N).