LeetCode:Best Time to Buy and Sell Stock

来源:互联网 发布:阿里数据分析师面试 编辑:程序博客网 时间:2024/06/16 09:15

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.

// Source : https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock/  // Author : Chao Zeng    // Date   : 2014-12-26  class Solution {public:    int maxProfit(vector<int> &prices) {int n = prices.size();if (n == 0)return 0;int mp[n];//表示以prices[i]结尾的max profitint minnumber = prices[0];memset(mp,0,sizeof(mp));for (int i = 1; i < n; i++){if (minnumber > prices[i])minnumber = prices[i];int dis = prices[i] - minnumber;if (mp[i-1] < dis)mp[i] = dis;elsemp[i] =mp[i-1];}return mp[n-1];    }};


0 0