Pages

Tuesday 22 December 2015

Naïve String Matching Algorithm

Naïve String Matching Algorithm

It employs a Brute Force technique to identify the presence of a pattern in the given text.

It is not efficient algorithm because it takes the time complexity of the algorithm to check for a sub string is O((m-n)n) where m is the length of the text and n is the length of the pattern (sub string) to be searched.

There is no preprocessing is required for this algorithm unlike KMP algorithm.

Preprocessing time: 0 (no preprocessing)
Matching time: O((n-m)m).

NaiveStringMatcher(text, pattern)
tLen ← length [text]
pLen ← length [pattern]

for i ← 0 to tLen - pLen do
     mCount = 0;
for j ← 0 to pLen do
    if text[i] != pattern[j+i]
        break;
    mCount++;
     if(mCount == pLen)
           return Valid match found at position : + i!!



public class NaiveStringMatch {
      public static void main(String[] args) {
            String text = "I love to work on the algorithms!";
            String pattern = "the algorithms";
            naiveStringMatcher(text, pattern);
      }

      /**
       * Implementation of Naive String matching algorithm.
       * @param text
       * @param pattern
       */
      private static void naiveStringMatcher(String text, String pattern) {

            char[] txtArr = text.toCharArray();
            char[] patArr = pattern.toCharArray();

            int tLen = txtArr.length;
            int pLen = patArr.length;

            for (int i = 0; i < tLen - pLen; i++) {

               int charMatchCount = 0;
               for (int j = 0; j < pLen; j++) {

                    /**
                     * If pattern mismatch, break next searching point.
                     **/
                     if (patArr[j] != txtArr[i + j]) {
                          break;
                     }
                     charMatchCount++;

               }
               if (charMatchCount == pLen) {
                     print("String found at "+(i+1)+" position!!");
                     break;
               }
            }
      }

      private static void print(String string) {
            System.out.println(string);
      }
}
Output:
String found at 19 position!!

Tuesday 8 December 2015

Maximize the Stock profit

Problem Statement
Design algorithms to predicting the maximum profit when you know what the share price of ORANGE FT Group will be for the next N days.

Conditions:
1. You can either buy one share of ORANGE FT Group each day.
2. You can sell any number/no share of shares of Orange owned by you.
What is the maximum profit you can obtain with an optimum trading strategy?

Input
First line: Number of test cases.
Second line: Number of days.
Third line: Share value on particular day.

Output
Maximum profit of each day.

Solution#1: Brute force
  1. Find in maximum value on which share can be sell.
    L
    argest element in the right current element.
  2. If there is any profit to sell the share add it the PROFIT.
  3. Repeat the step#1 and step#2.

Time complexity: O(n^2).
Space complexity: O(1).

Solution#2: Dynamic Programming.
  1. Find out the maximum value of the right side of index and keep update the value in maxArr [] till zero index.
    maxArr[i] = Math.max(maxArr[i+1], values[i]);
  2. To find maximum earn to buy a share:
    p
    rofit = profit + Math.max(maxArr[r]-values[r],0);

Values[]:
10
20
30
40
50

MaxArray[]:
Maximum element from right to left.
50
50
50
50
50

profit = profit + Math.max(maxArr[r]-values[r],0);

Time complexity: O(n).
Space complexity: O(n).

import java.io.*;
importjava.util.*;
importjava.text.*;
importjava.math.*;
importjava.util.regex.*;

public class Solution {
     public static voidmain(String[] args) throws Exception {
           BufferedReader reader = new BufferedReader(
                                 new InputStreamReader(System.in));

           int count = Integer.parseInt(reader.readLine());
           for(inti=0;i<count;i++) {
                int ip_size = Integer.parseInt(reader.readLine());
                int[] values = new int[ip_size];
                String valStr = reader.readLine();
                int j = 0;
                for(String el : valStr.split(" ")) {
                     values[j] = Integer.parseInt(el);
                     j++;
                }

                int[] maxArr = new int[values.length];

                maxArr[values.length-1] = values[values.length-1];
                int q = values.length-2;
                while(q>=0) {
                     maxArr[q] = Math.max(maxArr[q+1],values[q]);
                     q--;
                }
                long profit = 0;
                for(int r=0;r<ip_size;r++) {
                     profit = profit +
                          Math.max(maxArr[r]-values[r],0);
                }
                System.out.println(profit);
           }
     }
}
Input:
1
5
10 20 30 40 50
Output:
100

Reference

Thursday 3 December 2015

Stock Buy Sell for Maximum Profit

The cost of a stock on a day is given in a list, find the max profit that we can make by buying and selling once.

Example:
If the given array is {90, 170, 700, 300, 30, 525, 685}.
Maximum profit: 685 – 30.

90
170
700
300
30
525
685

Solution:
90
170
700
300
30
525
685

minArray[]: Minimum element in left sub-array of every index.
90
90
90
90
30
30
30

maxArray[]: Maximum element in right sub-array of every index.
700
700
700
685
685
685
685

difference[]: Difference of minArray[i]-maxArray[i].
610
610
610
595
655
655
655


Maximum value in difference array will be treated as result.

Stock Buy Sell for Maximum Profit

Stock Buy Sell for Maximum Profit
The cost of a stock on a day is given in a list, find the max profit that we can make by buying and selling once.

Example:
If the given array is {90, 170, 700, 300, 30, 525, 685}.
Maximum profit: 685 – 30.

90
170
700
300
30
525
685

Solution:
90
170
700
300
30
525
685

minArray[]: Minimum element in left sub-array of every index.
90
90
90
90
30
30
30

maxArray[]: Maximum element in right sub-array of every index.
700
700
700
685
685
685
685

difference[]: Difference of minArray[i]-maxArray[i].
610
610
610
595
655
655
655


Maximum value in difference array will be treated as result.