LeetCode - 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.
Java Solution :
class Solution {
    public int maxProfit(int[] prices) {
        int minPrice = Integer.MAX_VALUE;
        int maxProfit = 0;
        
        for(int i =0 ; i < prices.length ; i++){
            if(prices[i] < minPrice)
                minPrice = prices[i];
            else if(prices[i]-minPrice > maxProfit)
                maxProfit = prices[i] - minPrice;
        }
        return maxProfit;
    }
}

Time Complexity : O(n)
Space Complexity : O(1)

Other Solution :

class Solution {
    public int maxProfit(int[] prices) {
        int maxProfit = 0;
        for(int i =0 ; i < prices.length ; i++){
            for(int j = i+1; j < prices.length ; j++){
                maxProfit = Math.max(maxProfit,prices[j]-prices[i]);
            }
        }
        return maxProfit;
    }
}

Time Complexity : O(n*n)
where n is the length of input array length.
Space Complexity : O(1)


LeetCode - Climbing Stairs

You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Note: Given n will be a positive integer.
Example 1:
Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
Example 2:
Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
Java Solution :
class Solution {
    public int climbStairs(int n) {
        if(n == 0 || n == 1 || n == 2)
            return n;
        int previousstep = 2;
        int prepreviousstep = 1;
        for(int i = 3; i <= n ; i++){
            int current = previousstep + prepreviousstep;
            prepreviousstep = previousstep;
            previousstep = current;
        }
        return previousstep;
    }
}
Time Complexity : O(n)
Space Complexity : O(1)
Approach : Dynamic Programming Tabularization.

HTTP Methods , Restful API Methods , URI examples

GET METHOD :

HTTP GET http://oms.com/orders/1
HTTP GET http://oms.com/orders

POST METHOD :

HTTP POST http://oms.com/orders/
HTTP POST http://oms.com/users/1/products

The difference between the POST and PUT APIs can be observed in request URIs. POST requests are made on resource collections, whereas PUT requests are made on an individual resource.

PUT METHOD :
HTTP PUT http://oms.com/orders/1/gg@gmail.com
HTTP PUT http://oms.com/users/2/orders/2

DELETE METHOD :

HTTP DELETE http://oms.com/orders/2
HTTP DELETE http://oms.com/users/3

PATCH METHOD :

PATCH is used to partial update on a  resource not like PUT which is used for entire resource update.

HTTP PATCH http://oms.com/orders/1/users/2/hh@gmail.com



What is the difference between PUT and POST methods in Rest API ?

PUT method is idempotent. Which means it produces same result . How many times you call that mention the result will be same.

Where Post method will produce different result when ever you call that function.

Post method is used to create a new resource.

PUT method is used in general to update a resource .



LeetCode - Excel Sheet Column Title

Given a positive integer, return its corresponding column title as appear in an Excel sheet.
For example:
    1 -> A
    2 -> B
    3 -> C
    ...
    26 -> Z
    27 -> AA
    28 -> AB 
    ...
Example 1:
Input: 1
Output: "A"
Example 2:
Input: 28
Output: "AB"
Example 3:
Input: 701
Output: "ZY"
Java Solution :
class Solution {
    public String convertToTitle(int n) {
        
        StringBuilder sb = new StringBuilder();
        
        while(n > 0){
            n--;
            char ch = (char) (n%26 + 'A');
            n = n/26;
            sb.append(ch);
        }
        sb.reverse();
        return sb.toString();
        
    }
}

Top 10 Books to Learn Java

For Freshers / Beginners :

1. Head First Java Current Edition : 2nd  by Kathy Sierra

https://www.amazon.com/Head-First-Java-Kathy-Sierra/dp/0596009208

2. Clean Code by Robert C. Martin

https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882

3. Java the Complete Reference Eleventh Edition  by Herbert Schildt

https://www.amazon.com/Java-Complete-Reference-Eleventh/dp/1260440230

4. Java Concurrency in Practice by Brain Goetz

https://www.amazon.com/Java-Concurrency-Practice-Brian-Goetz/dp/0321349601

5.  Effective Java by Joshua Bloch

https://www.amazon.com/Effective-Java-2nd-Joshua-Bloch/dp/0321356683


For Experienced Java Professionals:


6. Java A Beginner's Guide Eigth Edition by Herbert Schildt

https://www.amazon.com/Java-Beginners-Eighth-Herbert-Schildt/dp/1260440214

7.  Java Performance Definitive Guide  by Scott Oaks

https://www.amazon.com/Java-Performance-Definitive-Guide-Getting/dp/1449358454

8. Spring in action by Craig Walls 5th edition

https://www.amazon.com/Spring-Action-Craig-Walls/dp/1617294942

9.  Test Driven : TDD and Acceptance TDD for Java Developers 1st Edition

https://www.amazon.com/Test-Driven-Acceptance-Java-Developers/dp/1932394850

10. Mastering Java Machine Learning



https://www.amazon.com/Mastering-Java-Machine-Learning-architectures-ebook/dp/B01KOG6SW8














LeetCode - Moving Average from Data Stream

Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
Example:
MovingAverage m = new MovingAverage(3);
m.next(1) = 1
m.next(10) = (1 + 10) / 2
m.next(3) = (1 + 10 + 3) / 3
m.next(5) = (10 + 3 + 5) / 3

Java Solution:
class MovingAverage {

    /** Initialize your data structure here. */
    private Queue<Integer> q;
    private double sum;
    private int maxSize;
    public MovingAverage(Integer size) {
        q = new LinkedList<Integer>();
        maxSize = size;
        sum = 0;
    }
    
    public double next(int val) {
        if(q.size() != maxSize){
            q.offer(val);
            sum+=val;
            return sum / q.size();
        }else{
            sum-=q.peek(); // subtracting from sum before removing the first element
            q.poll();
            q.offer(val);
            sum+=val;
            return sum / q.size();
        }
    }
}

/**
 * Your MovingAverage object will be instantiated and called as such:
 * MovingAverage obj = new MovingAverage(size);
 * double param_1 = obj.next(val);
 */

Featured Post

H1B Visa Stamping at US Consulate

  H1B Visa Stamping at US Consulate If you are outside of the US, you need to apply for US Visa at a US Consulate or a US Embassy and get H1...