Maximum sum of non adjacent elements

Dynamic Programming 1D DP Medium
  • This problem demonstrates the concept of dynamic programming, which is a method for solving problems by breaking them down into simpler subproblems, and storing the solutions of these subproblems to avoid solving them repeatedly
  • In real-world applications, dynamic programming is extensively used in optimization problems
  • One popular example is Google Maps, where dynamic programming algorithms are used to find the shortest path between two locations, maximizing the efficiency of the route while minimizing travel time

Given an integer array nums of size n. Return the maximum sum possible using the elements of nums such that no two elements taken are adjacent in nums.


A subsequence of array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements.

Examples:

Input: nums = [1, 2, 4]

Output: 5

Explanation: [1, 2, 4], the underlined elements are taken to get the maximum sum.

Input: nums = [2, 1, 4, 9]

Output: 11

Explanation: [2, 1, 4, 9], the underlined elements are taken to get the maximum sum.

Input: nums = [1, 7, 16, 8]

Constraints

  • n == nums.length
  • 1 <= n <= 105
  • 0 <= nums[i] <= 1000

Hints

  • "Consider the two choices at each step i: Take nums[i] → Add nums[i] to the sum and skip the next element (i+1). Skip nums[i] → Move to the next element (i+1) without adding anything."
  • "Using dynamic programming (O(n)), we store the dp[] values to avoid redundant calculations. Further optimization reduces space complexity from O(n) to O(1), using two variables to track dp[i-1] and dp[i-2]."

Company Tags

Seagate Technology Zomato Salesforce eBay Zoho Flipkart NVIDIA Red Hat Activision Blizzard Oracle HCL Technologies Qualcomm MongoDB Alibaba McKinsey & Company Visa Mastercard Byju's Rockstar Games Ubisoft Chewy Cerner Snowflake ARM Bungie Google Microsoft Amazon Meta Apple Netflix Adobe