Download as pdf or txt
Download as pdf or txt
You are on page 1of 37

Experiment1.

Student Name: YASH RAJ UID: 21BCS11765


Branch:BE-CSE Section/Group:CC-649
Semester: 6 Date of Performance:13-01-2024
Subject Name: Advance Programming lab-2
Subject Code:21CSP-351

1. Aim:
● To Solve the Jump Game 2
● ● To Solve the 3 SUM Problem
2. Objective:
● You are given a 0-indexed array of integers nums of length n. You are initially
positioned at nums[0].
● Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such
that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.

3. Algo. /Approach and output:


class Solu)on {
public sta)c int finder(int nums[],int index,int dp[]){
if(index==nums.length-1){
return 0;
}
if(dp[index]!=-1){
return dp[index];
}
int npick=Integer.MAX_VALUE;
for(int i=1;i<=nums[index];i++){
int pick=Integer.MAX_VALUE;
if(i+index<nums.length){
pick=finder(nums,i+index,dp);
if(pick!=Integer.MAX_VALUE)
npick=Math.min(pick+1,npick);
}
}
return dp[index]=npick;
}
public int jump(int[] nums) {
int dp[]=new int[nums.length];
Arrays.fill(dp,-1);
return finder(nums,0,dp);
}
}

class Solu)on {

public List<List<Integer>> threeSum(int[] nums) {


int target = 0;

Arrays.sort(nums);

Set<List<Integer>> s = new HashSet<>();

List<List<Integer>> output = new ArrayList<>();

for (int i = 0; i < nums.length; i++){

int j = i + 1;

int k = nums.length - 1;

while (j < k) {

int sum = nums[i] + nums[j] + nums[k];

if (sum == target) {

s.add(Arrays.asList(nums[i], nums[j], nums[k]));

j++;

k--;

} else if (sum < target) {

j++;

} else {

k--;

output.addAll(s);

return output;

}
Experiment1.2

Student Name: YASH RAJ UID: 21BCS11765


Branch: BE-CSE Section/Group:CC-649-A
Semester: 6 Date of Performance:17-01-2024
Subject Name: Advance Programming lab-2
Subject Code:21CSP-351
1. Aim: To demonstrate the concept of
String-Matching algorithms.
Problem1: https://leetcode.com/problems/rotate-string/

Probem2: https://leetcode.com/problems/repeated-string-match/

2. Objective:
The problems are to find an integer s, called a valid shift where 0 ≤ s < n-m and T [s+1……s+m]
= P [1…… m]. In other words, to find even if P in T, i.e., where P is a substring of T. The items of
P and T are characters drawn from some finite alphabet such as {0, 1} or {A, B.

3. Algo. /Approach and output: class


Solu)on {
public boolean rotateString(String A, String B) {
if(A == null || B == null) {
//throw excep)on on A and B both being null?
return false;
}
if(A.length() != B.length()) {
return false;
}
if(A.length() == 0) {
return true;
}
for(int i = 0; i < A.length(); i++) {
if(rotateString(A, B, i)) {
return true;
}
}
return false;
}

private boolean rotateString(String A, String B, int


rota)on) {
for(int i = 0; i < A.length(); i++) {
if(A.charAt(i) !=
B.charAt((i+rota)on)%B.length())) {
return false;
}
}
return true;
}
}

class Solu)on {
public int
repeatedStringMatch(String a, String b) {
String copyA = a; int count
=1; int repeat =
b.length()/a.length(); for(int
i=0;i<repeat+2;i++){
if(a.contains(b)){
return count;
}
else{
a+=copyA;
count++;
}
}
return -1;

}
}
Time Complexity: O(N * M)

Learning Outcomes :
• Understanding String Repetition.
• Substring Matching Strategies.
•Problem Solving Skills.
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

Experiment 1.3
Student Name: Yash Raj UID: 21BCS11765
Branch: BE-CSE Section/Group: CC-649-A
Semester: 6th Date of Performance: 31-01-2024
Subject Name: Advance Programming-2 Subject Code: 21CSP-251

1. Aim:
• To Solve the Last Stone Weight.
• To Solve the Cheapest Flight Booking with K stops.

2. Objective:
• You are given an array of integers stones where stones[i] is the weight of
the ith stone. We are playing a game with the stones. On each turn, we
choose the heaviest two stones and smash them together. Suppose the
heaviest two stones have weights x and y with x <= y.
• There are n cities connected by some number of flights. You are given an
array flights where flights[i] = [fromi, toi, pricei] indicates that there is a
flight from city fromi to city toi with cost pricei.

3. Algo. /Approach and output:


class Solution {
public int lastStoneWeight(int[] stones) {
Arrays.sort(stones);
ArrayList<Integer> list = new ArrayList<>();
for(int i=0; i<stones.length; i++) {
list.add(stones[i]);
}
while(list.size() > 1) {
int val1 = list.get(list.size()-1);
int val2 = list.get(list.size()-2);
list.remove(list.size()-1);
list.remove(list.size()-1);
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

if(val1>val2 || val2>val1) {
list.add(Math.abs(val1-val2));
}
Collections.sort(list);
}
if(list.size()==1) {
return list.get(0);
}
else {
return 0;
}
}
}

class Solution {
public int findCheapestPrice(int n, int[][] a, int src, int dst, int k) {
List<List<List<Integer>>> graph = new ArrayList<>();
int i,m=a.length;
for(i=0;i<n;i++)
graph.add(new ArrayList<>());
for(i=0;i<m;i++)
{
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

ArrayList<Integer> tmp=new ArrayList<>();


tmp.add(a[i][1]); tmp.add(a[i][2]);
graph.get(a[i][0]).add(tmp);
}
int dp[][]=new int[n][k+2];
for(int it[]:dp)
Arrays.fill(it,-1);
int ans=dfs(graph,src,dst,k+1,dp);
return ans==Integer.MAX_VALUE?-1:ans;
}
public int dfs(List<List<List<Integer>>> graph,int src,int dst,int k,int dp[][])
{
if(k<0) return Integer.MAX_VALUE;
if(src==dst) return 0;
if(dp[src][k]!=-1) return dp[src][k];
int min=Integer.MAX_VALUE;
for(List<Integer> it:graph.get(src))
{
int cho=it.get(0); int price=it.get(1);
int cheap=dfs(graph,cho,dst,k-1,dp);
if(cheap!=Integer.MAX_VALUE)
min=Math.min(min,cheap+price);
}
return dp[src][k]=min;
}
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

Time Complexity: 1ST -O(n) 2nd-O(n + m)

Learning Outcomes:

1.Critical Thinking and Analysis.

2.Problem-Solving Skills.

3.Optimization Techniques.
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

Experiment – 2.1
Student Name: Yash Raj UID: 21BCS11765
Branch: BE-CSE Section/Group: 649 ‘A’
Date of Performance: 7th Feb 2024 Semester: 6
Subject Name: Advanced Programming Lab - II Subject Code: 21CSP-351

1. Aim:
• To Solve symmetric tree.
• To Solve balanced binary tree.

2. Objective:

1) Problem statement – Given the root of a binary tree, check whether it is a


mirror of itself (i.e. – symmetric around its center)

2) Problem Statement – Given a binary tree, determine if it is heightbalanced.

3. Algorithm, Script and Output:

Problem 1:
Algorithm:

The provided code aims to determine whether a binary tree is symmetric,


meaning that it is mirror image of itself around its center. Here is algorithm of
these two function:

1) isMirror Function:
• This function takes two tree nodes, left and right, as input and checks
if they are mirror images of each other.
• If both left and right are nullptr, it returns true, indicating that they are
symmetric.
• If either left or right is nullptr (but not both), it returns false, indicating
asymmetry.
• Otherwise, it checks if the values of the current nodes are equal and
recursively calls isMirror for the left subtree of left with the right
subtree of right and vice versa.
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
•If all recursive calls return true and the values of the current nodes are
equal, it returns true; otherwise, it returns false.
2) isSymmetric Function:
• This function checks if the given tree root is symmetric.
• If root is nullptr, it returns true (an empty tree is symmetric by
definition).
• Otherwise, it calls isMirror with the left and right subtrees of the root.
• If isMirror returns true, it means the tree is symmetric, so it returns
true; otherwise, it returns false.

Code:

class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
if (root == null) {
return false;
}

if (root.left == null && root.right == null) {


return targetSum == root.val;
}

boolean leftSum = hasPathSum(root.left, targetSum - root.val);


boolean rightSum = hasPathSum(root.right, targetSum - root.val);

return leftSum || rightSum;


}
}
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

Output:

Time and Space Complexity:


The time complexity of this program is O(N).
The space complexity is O(N).
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

Problem 2: Algorithm:

The given code implements two functions:


1. getHeight(TreeNode* root): This function calculates the height of a binary
tree rooted at root. If the tree is balanced, it returns the height of the tree;
otherwise, it returns -1.
2. isBalanced(TreeNode* root): This function checks if a binary tree rooted at
root is balanced. It utilizes the getHeight function to determine if the tree is
balanced or not.

Here's a simple algorithmic explanation of how the code works:


1. getHeight Function:
• If the root is nullptr, return 0 (height of an empty tree).
• Recursively calculate the heights of the left and right subtrees.
• If either subtree's height is -1 (indicating it's unbalanced) or the
absolute difference between the heights of left and right subtrees is
greater than 1, return -1 (indicating unbalanced).
• Otherwise, return the height of the current node, which is 1 plus the
maximum height of its left and right subtrees.
2. isBalanced Function:
• If the root is nullptr, return true (empty tree is considered balanced).
Check if the height of the tree (obtained from getHeight function) is -
1. If it is, return false, indicating the tree is unbalanced; otherwise,
return true.

Code:

class Solution {
public boolean isBalanced(TreeNode root) {
// If the tree is empty, we can say it’s balanced...
if (root == null) return true;
// Height Function will return -1, when it’s an unbalanced tree...
if (Height(root) == -1) return false;
return true;
}
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

// Create a function to return the “height” of a current subtree using recursion...


public int Height(TreeNode root) {
// Base case...
if (root == null) return 0;
// Height of left subtree...
int leftHeight = Height(root.left);
// Height of height subtree...
int rightHight = Height(root.right);
// In case of left subtree or right subtree unbalanced, return -1...
if (leftHeight == -1 || rightHight == -1) return -1;
// If their heights differ by more than ‘1’, return -1...
if (Math.abs(leftHeight - rightHight) > 1) return -1;
// Otherwise, return the height of this subtree as max(leftHeight, rightHight) + 1...
return Math.max(leftHeight, rightHight) + 1;
}
}
OUTPUT:

Time and Space complexity:

• The overall time complexity of the code O(N)


• Space complexity of the code is O(N) in worst case scenario.
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

Learning Outcomes:

1. I understood recursive tree traversal algorithms for determining tree


properties, such as symmetry and balance.
2. I gained insight into the importance of recursive base cases and
conditional logic for handling tree structures effectively.
3. It enhanced Enhancing proficiency in assessing time and space
complexity in recursive algorithms to evaluate their efficiency and
scalability.
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

Experiment – 2.2
Student Name: Yash Raj UID: 21BCS11765
Branch: BE-CSE Section/Group: 649 ‘A’
Date of Performance: 21st Feb 2024 Semester: 6
Subject Name: Advanced Programming Lab - II Subject Code: 21CSP-351

1. Aim:
 To Solve the skyline problem.
 To Solve is graph bipartite.

2. Objective:

1) Problem statement – A city's skyline is the outer contour of the silhouette


formed by all the buildings in that city when viewed from a distance.
Given the locations and heights of all the buildings, return the skyline
formed by these buildings collectively.
The geometric information of each building is given in the array buildings
where buildings[i] = [lefti, righti, heighti]:
lefti is the x coordinate of the left edge of the ith building.
righti is the x coordinate of the right edge of the ith building.
heighti is the height of the ith building.
You may assume all buildings are perfect rectangles grounded on an
absolutely flat surface at height 0.
The skyline should be represented as a list of "key points" sorted by their
x-coordinate in the form [[x1,y1],[x2,y2],...]. Each key point is the left
endpoint of some horizontal segment in the skyline except the last point in
the list, which always has a y-coordinate 0 and is used to mark the
skyline's termination where the rightmost building ends. Any ground
between the leftmost and rightmost buildings should be part of the
skyline's contour.
Note: There must be no consecutive horizontal lines of equal height in the
output skyline. For instance, [...,[2 3],[4 5],[7 5],[11 5],[12 7],...] is not
acceptable; the three lines of height 5 should be merged into one in the
final output as such: [...,[2 3],[4 5],[12 7],...]

2) Problem Statement – There is an undirected graph with n nodes, where


each node is numbered between 0 and n - 1. You are given a 2D array
graph, where graph[u] is an array of nodes that node u is adjacent to. More
formally, for each v in graph[u], there is an undirected edge between node
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
u and node v. The graph has the following properties:
There are no self-edges (graph[u] does not contain u).
There are no parallel edges (graph[u] does not contain duplicate values).
If v is in graph[u], then u is in graph[v] (the graph is undirected).
The graph may not be connected, meaning there may be two nodes u and v
such that there is no path between them.
A graph is bipartite if the nodes can be partitioned into two independent
sets A and B such that every edge in the graph connects a node in set A
and a node in set B.
Return true if and only if it is bipartite.

3. Algorithm, Script and Output:

Problem 1:
Algorithm:

1. Define a function getSkyline that takes a vector of vectors buildings


representing the buildings' coordinates and heights and returns a vector of
vectors ans representing the skyline.
2. Initialize an empty vector ans to store the skyline.
3. Initialize a multiset pq with value 0. This will represent the heights of the
buildings, with the 0 value indicating the ground level.
4. Create a vector of pairs points to store the critical points where the heights
change, along with their respective heights. Each pair contains the x-
coordinate and the negative height of the left edge of a building, and the x-
coordinate and the positive height of the right edge of a building.
5. Iterate through each building in the input buildings: a. Add pairs of critical
points for each building to the points vector.
6. Sort the points vector based on the x-coordinates of the critical points.
7. Initialize a variable ongoingHeight to 0 to keep track of the current height.
8. Iterate through each critical point in the sorted points vector:
a. Retrieve the current point's x-coordinate and height.
b. If the height is negative, insert its absolute value (the building's
height) into the multiset pq.
c. If the height is positive, erase its corresponding height from the
multiset pq.
d. Find the maximum height in the multiset pq and update
ongoingHeight.
e. If the ongoingHeight changes, add the current point's x-coordinate
and the new ongoingHeight to the ans vector.
9. Return the ans vector containing the skyline.
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

Code:
class Solution {
public:
vector<vector<int>> getSkyline(vector<vector<int>>& buildings) {
vector<vector<int>> ans;
multiset<int> pq{0};

vector<pair<int, int>> points;

for(auto b: buildings){
points.push_back({b[0], -b[2]});
points.push_back({b[1], b[2]});
}

sort(points.begin(), points.end());

int ongoingHeight = 0;

// points.first = x coordinate, points.second = height


for(int i = 0; i < points.size(); i++){
int currentPoint = points[i].first;
int heightAtCurrentPoint = points[i].second;

if(heightAtCurrentPoint < 0){


pq.insert(-heightAtCurrentPoint);
} else {
pq.erase(pq.find(heightAtCurrentPoint));
}

// after inserting/removing heightAtI, if there's a change


auto pqTop = *pq.rbegin();
if(ongoingHeight != pqTop){
ongoingHeight = pqTop;
ans.push_back({currentPoint, ongoingHeight});
}
}

return ans;
}
};
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

Output:

Time and Space Complexity:


 The time complexity of this program is O(NlogN).
 The space complexity is O(N).
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

Problem 2:
Algorithm:

1. Define a function isBipartite that takes a graph represented as an adjacency


list graph and returns true if the graph is bipartite, false otherwise.
2. Initialize a stack s to perform depth-first search (DFS).
3. Initialize a vector vis to keep track of visited nodes and their colors. The
value 0 indicates unvisited, 1 and 2 represent different colors.
4. Iterate through each node in the graph: a. If the node is already visited,
continue to the next node. b. Mark the current node as visited and assign it
the color 1. Push it onto the stack. c. While the stack is not empty, perform
DFS:
 Pop the top node curr from the stack.
 Get the adjacent nodes of curr from the adjacency list.
 For each adjacent node next, if it is not visited:
 Assign the opposite color of curr to next.
 Push next onto the stack.
 If next is already visited and has the same color as curr, return false
(graph is not bipartite).
5. If the DFS completes without finding conflicts, return true (graph is
bipartite).

Code:

class Solution {
public:
bool isBipartite(vector<vector<int>>& graph) {
int len = graph.size();
stack<int> s;
vector<int> vis(len);
for (int i = 0; i < len; i++) {
if (vis[i] > 0) continue;
vis[i] = 1;
s.push(i);
while (s.size() > 0) {
int curr = s.top();
s.pop();
vector<int> edges = graph[curr];
for (int next:edges)
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
if (vis[next] == 0) {
vis[next] = vis[curr] ^ 3;
s.push(next);
} else if (vis[curr] == vis[next]) return false;
}
}
return true;
}
};

Output:
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

Time and Space complexity:

 The overall time complexity of the code O(V+E)


 Space complexity of the code is O(V).

Learning Outcomes:

1. I got the understanding of tree traversal algorithms (e.g., depth-first


search) and their application in solving problems such as finding the
diameter of a binary tree..
2. I got familiar with graph traversal techniques (e.g., depth-first search)
and graph coloring principles for determining bipartite graphs,
enhancing problem-solving skills in graph-related scenarios.
3. It imporved. in algorithmic thinking, including handling complex data
structures (trees, graphs), optimizing time and space complexities, and
gaining insights into diverse problem-solving strategies.
Experiment 2.3

Student Name: Yash Raj UID: 21BCS11765


Branch: BE-CSE Section/Group:649-CC-A
Semester: 6 Date of Performance:28-02-2024
Subject Name: Advance Programming lab
Subject Code:21CSP-251

1. Aim:
• To Solve Count and Say
• To Solve Jewels and Stones
2. Objective:

• The count-and-say sequence is a sequence of digit strings defined by the


recursive formula: countAndSay(1) = "1" countAndSay(n) is the way you would
"say" the digit string from countAndSay(n-1), which is then converted into
a different digit string.

• Given a string representing types of stones that are jewels (J) and another
string representing the stones you have (S), the goal is to determine how
many stones in S are also jewels represented by J. The task is to provide
an efficient solution for this counting problem.

3. Algo. /Approach and output:

class Solution {

public String countAndSay(int n) {

if(n==1)

return "1";

String s=countAndSay(n-1);

int c=0;
StringBuilder ans=new StringBuilder();

for(int i=0;i<s.length();i++){

c++;

if(i==s.length()-1 || s.charAt(i)!=s.charAt(i+1)){

ans.append(c).append(s.charAt(i));

c=0;

return ans.toString();

2.Jewels and Stones:


class Solution {
public int numJewelsInStones(String jewels, String stones) {
int count = 0;
for (int i = 0; i < stones.length(); i++) {
if (jewels.indexOf(stones.charAt(i)) != -1) {
count++;
}
}
return count;
}
}

Time and Space Complexity:


• Time complexity of problem 1code is O(m * n) & space complexity is
O(1).
• Time complexity of problem 2 code is O(2^n) & space complexity is
O(2^n).

Learning Outcomes:

• Problem-solving with Strings: Both problems involve manipulating and


processing strings.
• Recursion: The "Count and Say" problem utilizes recursion to generate the
sequence.
Experiment 3.1

Student Name: Yash Raj UID: 21BCS11765


Branch: BE-CSE Section/Group:CC-649-A
Semester: 6 Date of Perform.:08-03-2024
Subject Name: Advance Programming lab
Subject Code:21CSP-251

1. Aim:
● To Solve the candy Problem
● To Solve Time to buy and sell the stock II
2. Objective:

● There are n children standing in a line. Each child is assigned a rating value given in the integer array
ratings.
● You are given an integer array prices where prices[i] is the price of a given stock on the ith day. On
each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the
stock at any time. However, you can buy it then immediately sell it on the same day.
3. Algo. /Approach and output:

class Solution {

public:
int candy(vector<int> &ratings)
{
int size=ratings.size();
if(size<=1)
return size;
vector<int> num(size,1);
for (int i = 1; i < size; i++)
{
if(ratings[i]>ratings[i-1])
num[i]=num[i-1]+1;
}
for (int i= size-1; i>0 ; i--)
{
if(ratings[i-1]>ratings[i])
num[i-1]=max(num[i]+1,num[i-1]);
}
int result=0;
for (int i = 0; i < size; i++)
{
result+=num[i];
// cout<<num[i]<<" ";
}
return result;
}
};

class Solution {
public:
int maxProfit(vector<int>& prices) {
int profit=0;
for(int i=1;i<prices.size();i++){
if(prices[i]>prices[i-1]){
profit+=(prices[i]-prices[i-1]);
}
}
return profit;
}
};
Experiment 3.2

Student Name: Yash Raj UID: 21BCS11765


Branch: BE-CSE Section/Group:CC-649-A
Semester: 6 Date of Performance:25-03-2024
Subject Name: Advance Programming lab
Subject Code:21CSP-251

1. Aim:
● To Solve the binary watch
● To Solve the Sticker to spell word
2. Objective:

● A binary watch has 4 LEDs on the top to represent the hours (0-11), and
6 LEDs on the bottom to represent the minutes (0-59). Each LED
represents a zero or one, with the least significant bit on the right.

● You would like to spell out the given string target by cutting
individual letters from your collection of stickers and rearranging
them. You can use each sticker more than once if you want, and you have
infinite quantities of each sticker.
Return the minimum number of stickers that you need to spell out target.
If the task is impossible, return -1.

3. Algo. /Approach and output:

class Solution {
public:
vector<string> readBinaryWatch(int turnedOn) {
vector<string> result;
for(int h=0;h<12;h++){
for(int m=0;m<60;m++){
if((__builtin_popcount(h)+__builtin_popcount(m))==turnedOn){
result.push_back(to_string(h)+(m<10 ? ":0" :
":")+to_string(m));
}
}
}
return result;
}
};

class Solution {
public:
int minStickers(vector<string>& stickers, string& target) {
int n = size(stickers);
unordered_set<string> visited;
vector<vector<int>> s_frequencies(n, vector<int>(26, 0));
for (int i = 0; i < n; ++i)
for (auto& c : stickers[i])
++s_frequencies[i][c - 'a'];
vector<int> t_frequency(26, 0);
for (auto& c : target)
++t_frequency[c - 'a'];
queue<vector<int>> q;
q.push(t_frequency);

for (int res = 0; size(q); ++res) {


for (int k = size(q); k > 0; --k) {
auto t_freq = q.front(); q.pop();
string t_str;
for (int i = 0; i < 26; ++i)
if (t_freq[i] > 0)
t_str += string(t_freq[i], i);

if (t_str == "") return res;


if (visited.count(t_str)) continue;
visited.insert(t_str);

char seeking = t_str[0];


for (auto& v : s_frequencies) {
if (v[seeking] > 0) {
q.push(t_freq); // Push first to copy t_freq
for (int i = 0; i < 26; ++i)
q.back()[i] -= v[i];
}
}
}
}

return -1;
}
};
Experiment 3.3

Student Name: Yash Raj UID: 21BCS11765


Branch:BE-CSE Section/Group:CC-649-A
Semester: 6 Date of Performance:10-04-2024
Subject Name: Advance Programming lab
Subject Code:21CSP-251

1. Aim:
● To Solve the Best time to buy and sell the stock
● To Solve the longest Palindromic substring
2. Objective:

● You are given an array prices where prices[i] is the price of a given stock
on the ith day.You want to maximize your profit by choosing a single day to
buy one stock and choosing a different day in the future to sell that
stock.

● Given a string s, return the longest palindromic substring in s.

3. Algo. /Approach and output:

class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.empty()){
return 0;
}
int maxprice=0;
int minprice=prices[0];
for(int i=1;i<prices.size();i++){
if(prices[i]<minprice){
minprice=prices[i];
}
else{
int currprofit=prices[i]-minprice;
maxprice=max(maxprice,currprofit);
}
}
return maxprice;
}
};

class Solution {
public:
std::string longestPalindrome(std::string s) {
if (s.length() <= 1) {
return s;
}

auto expand_from_center = [&](int left, int right) {


while (left >= 0 && right < s.length() && s[left] == s[right]) {
left--;
right++;
}
return s.substr(left + 1, right - left - 1);
};

std::string max_str = s.substr(0, 1);

for (int i = 0; i < s.length() - 1; i++) {


std::string odd = expand_from_center(i, i);
std::string even = expand_from_center(i, i + 1);
if (odd.length() > max_str.length()) {
max_str = odd;
}
if (even.length() > max_str.length()) {
max_str = even;
}
}

return max_str;
}
};

You might also like