leecode 解题总结:121. Best Time to Buy and Sell Stock

来源:互联网 发布:淘宝ashford 编辑:程序博客网 时间:2024/06/11 17:04
#include <iostream>#include <stdio.h>#include <vector>using namespace std;/*问题:Contributors: AdminSay 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.Example 1:Input: [7, 1, 5, 3, 6, 4]Output: 5max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)Example 2:Input: [7, 6, 4, 3, 1]Output: 0In this case, no transaction is done, i.e. max profit = 0.分析:给定一个数组,模拟股票价格,要求获取最大利润。也就是从数组中选取两个元素,并且满足较小的元素在前面,较大的元素在后面,求这样一个差值最大的两个元素。如果数组降序,直接返回利润为0。问题的关键在于不能简单的去找到最小值和最大值,必须满足较小的元素在前面,较大的元素在后的情况。因此,如果设定一个指向较小元素指针low从前向后遍历,设定一个指向较大元素的指针high从后向前遍历。假设数组为A。如果A[low] >= A[high],不能这样做。指针的走位收到其他元素的影响。这个应该是动态规划。如果采用暴力破解,罗列每个买入股票的位置和卖出股票的位置,时间复杂度就是O(n^2)如果采用以当前元素为中心,分别向左和向右扩散的方式,向左找到比自己最小的元素,向右找到比自己最大的元素,然后比较差值时间复杂度也是O(n^2)输入:67 1 5 3 6 457 6 4 3 142 1 7 452 4 1 7 11输出:50610超时,说明有比O(n^2)更好的方法。参考分治的情况。将数组划分成两部分。设数组为A[1...n]1】如果左边和右边都求出了有差值,记结果分别为lDiff = lMax - lMin,rDiff = rMax - rMin如果lMax <= rMin,diff=rMax - lMin否则,diff=max(lMax , rMax) - lMin,diff=max(diff ,lDiff, rDiff)2】左边和右边都没有求出差值,说明都是降序,易错,左右都无效,不能直接返回0。左边是降序,右边是降序,找出左边最小和右边最大,如果左边最小 < 右边最大,返回结果3】左边求出差值,右边没有求出,说明右边是降序排列,diff=max(lMax,右边最大元素)-lMin,右边最大元素是右边序列中第一个元素4】左边没有求出差值,右边求出差值,左边降序,左边序列中最后一个元素最小diff=rMax - min(rMin , 左边序列最小元素)报错:2 1 7 4,我的结果是0,预期结果是6。Input:[2,4,1,7,11] ,Output:9 ,Expected:10 发现漏掉了对1和7,11的比较,证明该分治算法是有问题的{1, 7, 4, 11}, if he gives {0, 6, -3, 7},关键:1 leecode解法:https://discuss.leetcode.com/topic/5863/sharing-my-simple-and-clear-c-solution/16一直记录从初始到当前元素的最小值,和最大利润(初始为0),如果当前元素 > 最小值,计算新的利润,如果新的利润 > 当前最大利润,更新最大利润。没想到可以通过记录一个最小元素来解决该问题,最小元素解决了需要双层循环的问题*/class Solution {public:    int maxProfit(vector<int>& prices) {        if(prices.empty()){return 0;}int size = prices.size();int minPrice = INT_MAX;int profitMax = 0;for(int i = 0 ; i < size ; i++){if(prices.at(i) < minPrice){minPrice = prices.at(i);}else{profitMax = max(profitMax , prices.at(i) - minPrice);}}return profitMax;}};void print(vector<int>& result){if(result.empty()){cout << "no result" << endl;return;}int size = result.size();for(int i = 0 ; i < size ; i++){cout << result.at(i) << " " ;}cout << endl;}void process(){ vector<int> nums; int value; int num; Solution solution; while(cin >> num ) { nums.clear(); for(int i = 0 ; i < num ; i++) { cin >> value; nums.push_back(value); } int result = solution.maxProfit(nums); cout << result << endl; }}int main(int argc , char* argv[]){process();getchar();return 0;}

0 0
原创粉丝点击