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 };
  • 相关阅读:
    synchronized的原理
    ThreadLocal是什么?使用场景有哪些?
    什么是死锁?死锁产生的原因?
    15-错误
    14-异常处理
    13-接口
    12-方法
    11-结构体
    10-指针
    09-字符串
  • 原文地址:https://www.cnblogs.com/Deribs4/p/5709718.html
Copyright © 2011-2022 走看看