The best time to buy and buy stocks

Source: Internet
Author: User

The best time to buy and buy stocks

The best time to buy and buy stocks

Description: Suppose there is an array whose I-th element is the price of a given stock on the I-th day. If you are allowed to complete a transaction at most once (for example, a stock transaction), design an algorithm to find the maximum profit.

Example

An array example [3, 2, 3, 1, 2] is provided, and 1 is returned.

 

I just made this question in LintCode. At first, it was because of the for loop nesting problem and the running time timed out. Is the following a substitute?

class Solution {public:    /**     * @param prices: Given an integer array     * @return: Maximum profit     */    int maxProfit(vector<int> &prices) {        // write your code here    /*if(pirces.size()==0){    return 0;}*/        if(prices.size()==0)        return 0;        int max=0,sum=prices.size();        int i,j;        for(i=0;i<sum-1;i++)        {            for(j=0;j<sum-1-i;j++)            {            if(prices[i]<prices[i+j+1]&&max<prices[i+j+1]-prices[i])                max=prices[i+j+1]-prices[i];            }         }    return max;    }};

 

Below I discard a for Loop

class Solution {public:    /**     * @param prices: Given an integer array     * @return: Maximum profit     */    int maxProfit(vector<int> &prices) {        // write your code here    /*if(pirces.size()==0){    return 0;}*/        if(prices.size()==0)        return 0;        int min=prices[0],max=0,sum=prices.size();        for(int i=0;i<sum-1;i++)        {            if(prices[i+1]<min)            {                min=prices[i+1];            }            else            {                if(max<prices[i+1]-min)                max=prices[i+1]-min;            }         }    return max;    }};

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.