Dynamic Programming: Basics and a Practical Example

Introduction: Dynamic programming is a problem-solving technique that can seem quite intimidating at first glance. However, once you grasp its fundamentals and see it in action, you'll find it to be a powerful tool in your coding arsenal. In this blog post, we'll demystify the basics of dynamic programming and walk through a practical example. We'll provide you with clear explanations and a complete Python program, so you can understand and apply this essential concept with confidence. Understanding Dynamic Programming: At its core, dynamic programming is all about breaking down a complex problem into smaller, overlapping subproblems. It's a technique used to efficiently solve problems by storing and reusing solutions to these subproblems, rather than recomputing them. This leads to significant improvements in runtime complexity. Example: Fibonacci Sequence with Dynamic Programming Let's start by tackling a classic problem: calculating Fibonacci numbers. The Fibonac...

Median of Two Sorted Arrays Solution | leetcode

Source

Solution :

class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        
        int merge[] = new int[nums1.length + nums2.length];
        int i = 0, j = 0, index = 0;
        
        while(i < nums1.length || j < nums2.length) {
            if(i < nums1.length && j < nums2.length) {
                if(nums1[i] <= nums2[j]) {
                   merge[index] = nums1[i];
                    i++;
                    index++;
                    continue;
                } else {
                    merge[index] = nums2[j];
                    j++;
                    index++;
                    continue;
                }
            }
            
            if(i < nums1.length) {
                merge[index] = nums1[i];
                i++;
                index++;
            } else {
                merge[index] = nums2[j];
                j++;
                index++;
            }
        }
       
        if((nums1.length + nums2.length)%2 == 0){
            return (merge[((nums1.length + nums2.length)-1) / 2] + merge[(nums1.length + nums2.length) / 2]) / 2.0;
        } else {
            return merge[(nums1.length + nums2.length) / 2];
        }
    }

}

Comments

Popular posts from this blog

Array Transformation | biweekly-contest-12 | leetcode | Java Solution

Dynamic Programming: Basics and a Practical Example

leetcode | Longest Substring Without Repeating Characters Solution