Computer Science & Engineering: Department of
Computer Science & Engineering: Department of
Experiment 3.3
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: