leetcode--Best Time to Buy and Sell Stock

1.题目描述

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.

2.解法分析

实际上就是给出了一个数组a,数组中元素值为整数,找出数组中任意a[i]-a[j]的最大值,其中需满足i>=j

此题是经典题型,最简单的解法是先将a转化为b,其中:b[i]= a[i+1]-a[i],然后求b[i]的子数组中和最大的一个(子数组可以为空),于是有了下面的代码:

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(prices.size() <=1)return 0;
        vector<int>::iterator iter;
        for(iter=prices.begin();iter!=prices.end()-1;++iter)
        {
            *iter = *(iter+1) - *iter;
        }
        
        int max = 0;
        int subSum =0;
        
        for(iter=prices.begin();iter!=prices.end()-1;++iter)
        {
            subSum = subSum + *iter;
            if(subSum>max)max = subSum;
            if(subSum <0)subSum=0;
        }
        
        return max;
        
    }
};
posted @ 2013-08-10 13:32  曾见绝美的阳光  阅读(230)  评论(0编辑  收藏  举报