Best Time to Buy and Sell Stock, Leetcode 解题笔记

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.

逻辑题,维护一个lowest price和一个max profit,如果当前价格低于lowest price,更新lowest price。如果当前价格-lowest price大于max profit,更新max profit。

public class Solution {
    public int maxProfit(int[] prices) {
        int minV = Integer.MAX_VALUE;
        int maxP = 0;
        for(int i = 0; i < prices.length; i++){
            if(prices[i] < minV){
                minV = prices[i];
            }
            if(prices[i] - minV > maxP){
                maxP = prices[i] - minV;
            }
        }
        return maxP;
    }
}
Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s