You are on page 1of 3

Experiment - 10

Student Name: Naman Malik UID: 21BCS7798


Branch: BE-CSE Section/Group: SC-905-A
Semester: 6 Date of Performance:05-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:

Code 10.1:
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;
}
};

Time Complexity – O(N)


Space Complexity – O(1)
Code 10.2:
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:

Time Complexity – O(N)


Space Complexity – O(1)

You might also like