1. Climbing Stairs

https://leetcode.com/explore/interview/card/top-interview-questions-easy/97/dynamic-programming/569/

Dynamic Programming:

(There are also other methods exists such as recursion, but only apply DP this time)

  1. class Solution {
  2. public:
  3. int climbStairs(int n) { //basically a fibonacci
  4. if(n == 1)
  5. return 1;
  6. int curr = 1;
  7. int prev = 0;
  8. int next = 1;
  9. for(int i = 0; i < n; i++){
  10. curr = prev + next;
  11. prev = next;
  12. next = curr;
  13. }
  14. return curr;
  15. }
  16. };

2. Best Time to Buy and Sell Stock

https://leetcode.com/explore/interview/card/top-interview-questions-easy/97/dynamic-programming/572/

Dynamic Programming:

  1. class Solution {
  2. public:
  3. int maxProfit(vector<int>& prices) { //break the problem into
  4. //1. find the minimum value and
  5. //2. find the maximum profit that related to the minimum value
  6. int min_val = INT_MAX;
  7. int max_pro = 0;
  8. for(int i = 0; i < prices.size(); i++){
  9. if(prices[i] < min_val)
  10. min_val = prices[i];
  11. if((prices[i] - min_val) > max_pro)
  12. max_pro = prices[i] - min_val;
  13. }
  14. return max_pro;
  15. }
  16. };

3. Maximum Subarray

https://leetcode.com/explore/interview/card/top-interview-questions-easy/97/dynamic-programming/566/

Dynamic Programming:

  1. class Solution {
  2. public:
  3. int maxSubArray(vector<int>& nums) {
  4. if(nums.size()==1)
  5. return nums[0];
  6. int max_sum = nums[0];
  7. int cur_sum = 0;
  8. int n = nums.size();
  9. for(int i = 0; i < n; i++){
  10. cur_sum += nums[i];
  11. max_sum = max(max_sum, cur_sum);
  12. //update the maximum sum
  13. cur_sum = max(cur_sum, 0);
  14. //we only need the maximum sum in subarrays, so this is a kind of reset if the sum is negative
  15. //if cur_sum >= 0, the array before is worthy to be added
  16. }
  17. return max_sum;
  18. }
  19. };

4. Horse Robber

https://leetcode.com/problems/house-robber/