0% found this document useful (0 votes)
5 views

Computer Science & Engineering: Department of

The document describes an experiment to implement dynamic programming concepts. It provides two problems - to find maximum profit from buying and selling a stock, and to count the number of ways to reach the top of a staircase by climbing 1 or 2 steps each time. Solutions using dynamic programming are presented for both problems.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Computer Science & Engineering: Department of

The document describes an experiment to implement dynamic programming concepts. It provides two problems - to find maximum profit from buying and selling a stock, and to count the number of ways to reach the top of a staircase by climbing 1 or 2 steps each time. Solutions using dynamic programming are presented for both problems.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

DEPARTMENT OF

COMPUTER SCIENCE & ENGINEERING

Experiment 3.3

Student Name: Priyanshu Ghosh UID: 21BCS8733


Branch: CSE Section/Group:21BCS_CC-648
Semester: 6th Date of Performance: 14-04-2024
Subject Name: Advanced Programming Lab - 2 Subject Code: 21CSP-351

1. Aim: To implement the concept of Dynamic programming


2. Objective:
Problem 1: 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.
Return the maximum profit you can achieve from this transaction. If you cannot
achieve any profit, return 0.

3. Script and Output:


Problem 1:

class Solution {
public:
int maxProfit(std::vector<int>& prices) {
int buy = prices[0];
int profit = 0;
for (int i = 1; i < prices.size(); i++) {
if (prices[i] < buy) {
buy = prices[i];
} else if (prices[i] - buy > profit) {
profit = prices[i] - buy;
}
}
return profit;
}
};
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

OUTPUT:
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

Problem 2: - You are climbing a staircase. It takes n steps to reach the top. Each time you
can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Solution 2
class Solution {
public:
int climbStairs(int n) {
if (n == 1) return 1;
if (n == 2) return 2;

int n_1 = 1;
int n_2 = 2;
for (int i = 3; i <= n; ++i) {
int res = n_1 + n_2;
n_1 = n_2;
n_2 = res;
}
return n_2;
}
};

OUTPUT:

You might also like