FrontendChallenges is a collection of frontend interview questions and answers. It is designed to help you prepare for frontend interviews. It's free and open source.
difficulty: easy
title: Best Time to Buy and Sell Stock
type: question
template: typescript
tags: javascript, blind75, array, dynamic-programming
Question
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.
Constraints:
1 ≤ prices.length ≤ 10⁵
0 ≤ prices[i] ≤ 10⁴
Examples:
// Example 1:
const prices1 = [7, 1, 5, 3, 6, 4];
console.log(maxProfit(prices1));
// Output: 5
// Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
// Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
// Example 2:
const prices2 = [7, 6, 4, 3, 1];
console.log(maxProfit(prices2));
// Output: 0
// Explanation: In this case, no transactions are done and the max profit = 0.
Template
index.ts
export function maxProfit(prices: number[]): number {
}
index.test.ts
import { maxProfit } from './index';
describe('maxProfit', () => {
test('Example 1: Regular case with profit', () => {
expect(maxProfit([7, 1, 5, 3, 6, 4])).toBe(5);
});
test('Example 2: Decreasing prices', () => {
expect(maxProfit([7, 6, 4, 3, 1])).toBe(0);
});
test('Single day', () => {
expect(maxProfit([1])).toBe(0);
});
test('Two days with profit', () => {
expect(maxProfit([1, 2])).toBe(1);
});
test('Two days without profit', () => {
expect(maxProfit([2, 1])).toBe(0);
});
test('Same prices', () => {
expect(maxProfit([5, 5, 5, 5])).toBe(0);
});
test('Multiple peaks and valleys', () => {
expect(maxProfit([3, 2, 6, 1, 2])).toBe(4);
});
});
Info
Question
You are given an array
prices
whereprices[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.
Constraints:
Examples:
Template
index.ts
index.test.ts