medium Array

Maximum Subarray

Write a function maxSubArray that takes an array of integers and returns the contiguous subarray (containing at least one number) which has the largest sum.

Function Signature

function maxSubArray(nums);

Example 1:

Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: The subarray [4,-1,2,1] has the largest sum = 6.

Example 2:

Input: nums = [1]
Output: 1
Explanation: The largest sum subarray is [1].

Example 3:

Input: nums = [5,4,-1,7,8]
Output: 23
Explanation: The subarray [5,4,-1,7,8] has the largest sum = 23.

Solve this problem

Start your 7-day free trial to solve this problem in our code editor with instant feedback.

Start 7-Day Free Trial to Solve This Problem

Related Problems

Merge Intervals

medium

Write a function `mergeIntervals` that takes an array of intervals and merges all overlapping intervals. ## Function Signature ```function mergeIntervals(intervals);``` ### Example 1: > **Input:** `intervals = [[1, 3], [2, 6], [8, 10], [15, 18]]` \ > **Output:** `[[1, 6], [8, 10], [15, 18]]` \ > **Explanation:** Since intervals [1, 3] and [2, 6] overlap, merge them into [1, 6]. ### Example 2: > **Input:** `intervals = [[1, 4], [4, 5]]` \ > **Output:** `[[1, 5]]` \ > **Explanation:** Intervals [1, 4] and [4, 5] are considered overlapping.

Array

Best Time to Buy and Sell Stock

medium

Write a function `maxProfit` that takes an array where the `i-th` element is the price of a given stock on day `i`, and returns the maximum profit you can achieve by buying and selling one share of the stock. ## Function Signature ```function maxProfit(prices);``` ### Example 1: > **Input:** `prices = [7,1,5,3,6,4]` \ > **Output:** `5` \ > **Explanation:** Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. ### Example 2: > **Input:** `prices = [7,6,4,3,1]` \ > **Output:** `0` \ > **Explanation:** In this case, no transactions are done, i.e. max profit = 0.

Array

Three Sum

medium

Write a function `threeSum` that takes an array of integers and returns all unique triplets that sum up to zero. ## Function Signature ```function threeSum(nums);``` ### Example 1: > **Input:** `nums = [-1, 0, 1, 2, -1, -4]` \ > **Output:** `[[-1, -1, 2], [-1, 0, 1]]` \ > **Explanation:** The triplets that sum up to zero are [-1, -1, 2] and [-1, 0, 1]. ### Example 2: > **Input:** `nums = []` \ > **Output:** `[]` \ > **Explanation:** No triplets can be formed from an empty array. ### Example 3: > **Input:** `nums = [0]` \ > **Output:** `[]` \ > **Explanation:** No triplets can be formed from a single element.

Array