码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode#121Best Time to Buy and Sell Stock

时间:2015-05-17 18:52:08      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:interview   element   question   design   public   

Best Time to Buy and Sell Stock

 Total Accepted: 49995 Total Submissions: 153488My Submissions

Question Solution 


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.


Hide Tags

 Array Dynamic Programming

Have you met this question in a real interview? 

Yes

 

No

Discuss


分析:找最小最大值,计算最大利益


public class Solution {

    public int maxProfit(int[] prices) {

        int l=prices.length;

        if(l<=1)

            return 0;

        else

        {

            int min=prices[0];

            int max=prices[0];

            int maxp=0;

            int oldmaxp=0;

            for(int i=1;i<l;i++)

            {

                if(prices[i]<min)

                {

                    min=prices[i];

                    max=prices[i];

                    if(maxp>oldmaxp)

                        oldmaxp=maxp;

                }

                else

                {

                    if(prices[i]>max)

                    {

                        max=prices[i];

                        maxp=max-min;

                    }

                }

            }

            if(maxp>oldmaxp)

                return maxp;

            else

                return oldmaxp;

        }

    }

}


Leetcode#121Best Time to Buy and Sell Stock

标签:interview   element   question   design   public   

原文地址:http://7061299.blog.51cto.com/7051299/1652088

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!