Leetcode Best Time to Buy and Sell Stock

题目解析:
注意只能够买一次和卖一次股票
其实这个题目就是最大子列和的变形,他是求的矩阵【23,24,27,18,23,19,31】这样的一个矩阵的最大利润,当有些天的利润为负值,则另begin移到这一天作为开始,这与最大子列和的思想完全相同。
可参考我的最大子列和程序

// Author : yqtao
// Date : 2016-6.19
// Email :[email protected]
/********************************************************************************** * * 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. * **********************************************************************************/
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <set>
#include <map>
#include <algorithm>
using namespace std;
int maxProfit(vector<int> &price)
{
    int begin = 0, end = 0, max = 0;
    for (int i = 0; i < price.size(); i++)
    {
        end = i;
        int delta = price[end] - price[begin];
        if (delta <= 0)
            begin = i;
        if (delta > 0)
            max = delta;
    }
    return max;
}
//测试
int main()
{
    vector<int>price = { 23,24,27,18,23,19,31 };
    cout << maxProfit(price) << endl;//答案13即31-18=13利益最大
    //即利益为18的那天入手,利益31天出手,利益最大
}

你可能感兴趣的:(LeetCode)