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

    122. Best Time to Buy and Sell Stock II

    • Total Accepted: 96307
    • Total Submissions: 221716
    • Difficulty: Medium

    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).

    思路:相邻天的差价组成新的序列S={0,prices[1]-prices[0],prices[2]-prices[1]...prices[n-1]-prices[n-2]}。那么问题就可以转换为求序列S中多个连续子序列和的最大值,其实就是将S中所有大于0的元素相加。

    代码:

     1 class Solution {
     2 public:
     3     int maxProfit(vector<int>& prices) {
     4         if(prices.size()<2) return 0;
     5         int i,sum=0,cursum=0,n=prices.size();
     6         for(i=1;i<n;i++){
     7             int temp=prices[i]-prices[i-1];
     8             if(temp>0){
     9                 sum+=temp;
    10             }
    11         }
    12         return sum;
    13     }
    14 };
  • 相关阅读:
    点分治
    SG函数入门
    博弈论入门
    YY的gcd
    整除分块
    gcd约分函数的应用
    C++ 模拟类型(提高)
    C++数论题(博弈论)
    C++(gcd)的应用2。
    C++暴力约分(gcd).
  • 原文地址:https://www.cnblogs.com/Deribs4/p/5709718.html
Copyright © 2011-2022 走看看