ACWING83. Maximum profit shares (to prove safety offer)

Assuming that the price of a share in chronological order stored in an array, will profit once the sale of the shares may be obtained by how much?

For example, a stock price at certain times of the node [9, 11, 8, 5, 7, 12, 16, 14].

If we can at the price of 5 when buying and selling price is 16, it is able to gain maximum profit 11.

Sample
input: [9, 11, 8, 5, 7, 12, 16, 14]

Output: 11

class Solution {
public:
    int maxDiff(vector<int>& nums) {
        int mi = 2e9;
        int n = nums.size();
        if(!n) return 0;
        int ans = 0;
        for(int i = 0;i < n;i++) {
            mi = min(nums[i],mi);
            ans = max(ans,nums[i] - mi);
        }
        return ans;
    }
};
Published 844 original articles · won praise 28 · views 40000 +

Guess you like

Origin blog.csdn.net/tomjobs/article/details/104974466