zoukankan      html  css  js  c++  java
  • 122. Best Time to Buy and Sell Stock II

    Say you have an array for which the ith element is the price of a given stock on day i.

    Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

    我觉得这个就是贪心。对于prices[i] 往后找最后的prices[j] 然后把这段差值加上... 对于这种情况 1 5 5 10 当然取1买 10卖

    class Solution {
    public:
        int maxProfit(vector<int>& prices) {
            int x = 0,ans = 0;
            int n = prices.size();
            if (n <= 1) return 0;
            int be = 0;
            x = prices[be];
            for (int i = 0; i < n; ++i) {
                if (prices[i] >= x) {
                    x = prices[i];
                }
                else {
                    ans += x - prices[be];
                    be = i;
                    if (be < n)x = prices[be];
                }
            }
            if (x - prices[be] > 0) ans += x - prices[be];
            return ans;
        }
    };
  • 相关阅读:
    Binary Trees
    [POJ] String Matching
    Tree
    Maxmum subsequence sum problem
    poj 2104 划分树
    poj 2486 树形dp
    poj 1848 树形dp
    hdu 4578 线段树
    hdu 4585 set应用
    hdu 2412 树形DP
  • 原文地址:https://www.cnblogs.com/pk28/p/7229486.html
Copyright © 2011-2022 走看看