Leetcode–Best Time to Buy and Sell Stock

The Problem:

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.


  1. Keep track of max profit if sell at day i, and a min price to buy before day i.

Java Solution

public class Solution {
    public int maxProfit(int[] prices) {
        if(prices.length <=1)
            return 0;
        int maxProfit = 0;
        int minP = prices[0];
        for(int i = 1; i < prices.length; i++){
            maxProfit = Math.max(maxProfit, prices[i]-minP);
            minP = Math.min(minP, prices[i]);
        return maxProfit;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s