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

Experiment- 3.

Student Name: Amar Choubey UID: 21BCS11683


Branch: B.E-CSE Section/Group: SC-901-A
Semester: 6 Date of Performance:29-03-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:

a. 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.

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

3. Code:

Code (a.)

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;
}
};
Code (a.)
Code (b.)

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;
}
};
Output(b.)

Learning Outcomes:
a. To Understand the concept of Dynamic Programming.
b. To Analyze and Solve the Sub-strings and Palindrome Problem.

You might also like